Topic: Refactor model data conditional

Hey all,

I have a Entry model with a body (with RedCloth markup).  Sometimes this body contains a "more" tag and sometimes it doesn't.  This is used to create a "read more" break.  Currently, it is implemented like this:

entries/index.html.erb

<% @entries.each do |entry| %>
      ...
      <%= RedCloth.new(Entry.intro(entry.body)).to_html %><br />
      <%= link_to 'Read the full entry', user_entry_path(entry.user_id,entry), :class => "go" %>
      ...
<% end %>

models/entry.rb
validations...

  def self.intro(entry)
    if entry.include? "<!--more-->"
      entry_split = entry.split('<!--more-->')
      entry_split[0]
    else
      entry
    end
  end


Is this the best way to do this.  More importantly, and what I'm really looking for, if I wanted to make the appearance of the "link_to 'read the full...'..." similarly conditional, how would I do that?

Re: Refactor model data conditional

str = "foo bar sdsm <!--more-->hello"
str_2 = "foo bar sdsm hello"

puts str.split('<!--more-->').first # foo bar sdsm
puts str_2.split('<!--more-->').first # foo bar sdsm hello

you can use entry.split('<!--more-->').first directly

Re: Refactor model data conditional

1) us an instance method
2) use link_to_if

<% @entries.each do |entry| %>
      ...
      <%= RedCloth.new(entry.intro).to_html %><br />
      <%= link_to_if entry.body.include?("<!--more-->"), 'Read the full entry', user_entry_path(entry.user_id,entry), :class => "go" %>
      ...
<% end %>

models/entry.rb
  def intro
    @intro ||= self.body.split('<!--more-->').first
    #@intro kind of serves as a "cache" in case you whave to call #intro more than once on the same entry.
    #if not, you can remove it.
  end

Re: Refactor model data conditional

Thanks oscardb and Duplex.  Good suggestions about the first method.  Duplex, still learning about instance methods, need to read a little more I think.

It still seems checking for the "<!--more-->" twice is wrong.  If I have already determined in the model, why should I have to check it again to generate the link, right? 

What about maybe pulling out the logic into a partial or something?  Or is there somewhere else that makes sense to put the code?  Helper?  Thanks!