Variable class attribute access?

I have an array of similar objects which I need to sort based on one
their
many attributes.
For instance, Campaign has clicks, impressions and cost. I want to be
able
to dynamically sort by any of those attributes.

def sort_campaign_by(attr)
@campaigns.sort_by{ |c| c.#{attr} }
end

this (obviously) doesn’t work but hopefully my intentions are clear.
I’m
trying not to use a case statement - seems unnecessarily lengthy and
brittle.
note, I can’t sort them in the AR call, it needs to happen afterwards.

Anyone know how to do this?

thanks,
ed

Ed Hickey wrote:

I have an array of similar objects which I need to sort based on one
their
many attributes.
For instance, Campaign has clicks, impressions and cost. I want to be
able
to dynamically sort by any of those attributes.

def sort_campaign_by(attr)
@campaigns.sort_by{ |c| c.#{attr} }
end

this (obviously) doesn’t work but hopefully my intentions are clear.
I’m
trying not to use a case statement - seems unnecessarily lengthy and
brittle.
note, I can’t sort them in the AR call, it needs to happen afterwards.

Anyone know how to do this?

thanks,
ed

Try Array#sort or Array#sort!
http://www.ruby-doc.org/core/classes/Array.html#M000397

def sort_campaign_by(attr)
@campaigns.sort! { |a, b| a[attr] <=> b[attr] }
end

With active record objects, all the db stored attributes are accessible
as if the object was a hash. So “@user[:name]” is the same as
@user.name”. This makes it easier to dynamically call attributes.

You can also do it directly in the SQL you use to fetch your campaigns.

def index
@campaigns = Campaign.find(:all, :order => params[:sort_attr])
end

This option would probably be a bit faster. Let the database do what
it’s good at. However, if you need to use the data before it’s been
sorted this would not be an option for you.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs