What is the ruby equivalent of python's getattr

前端 未结 4 1121
慢半拍i
慢半拍i 2020-12-10 14:05

I am new to rails and trying to do a little refactoring (putting a partial renderer that lists titles in app/views/shared ) The renderer shows the dates along with the title

相关标签:
4条回答
  • 2020-12-10 14:41

    Matt's answer is correct for your exact question and I might be way off-mark with understanding your situation but...

    I'd pass the entire user object into the partial via the locals hash.

    render( 
      :partial => "shared/titles", 
      :object => @titles, 
      :locals => { :user => @user } 
    )
    

    Then within the partial call a helper method to return the correct date for each title, something like:

    <p><%= title_date_for_user(title, user) %></p>
    

    Pass the user and each title object to the helper method.

    def title_date_for_user(title, user)
      case user.date_i_like_to_see
      when "created_on"
        title_date = title.created_on
      when "updated_on"
        title_date = title.updated_on
      end
      return title_date.to_s(:short)
    end
    

    The date_i_like_to_see method resides in the User model and returns a string (created_on or updated_on) based on some logic particular to the given user.

    This approach tucks away most of the logic and keeps your view nice and clean. Plus it makes it simple to add further features specific to a given user later.

    0 讨论(0)
  • 2020-12-10 14:43

    You could add a function to the model like this

    def get_date(date)
      return created_on if date == 'created'
      return updated_on
    end
    
    0 讨论(0)
  • 2020-12-10 14:48

    The equivalent statement in Ruby:

    date_wanted = :created_on
    title_date = list_titles.send(date_wanted)
    
    0 讨论(0)
  • 2020-12-10 15:03

    I think the answer to the original question is send:

    irb(main):009:0> t = Time.new
    => Thu Jul 02 11:03:04 -0500 2009
    irb(main):010:0> t.send('year')
    => 2009
    

    send allows you to dynamically call an arbitrarily-named method on the object.

    0 讨论(0)
提交回复
热议问题