Models added functionality

Hello.

I have a piece of code (method) that I want all my models to have
available. What would be the best way to implement it?

Thanks

It’s just a piece of code to format data that will go in a
form.select. Something like this:

def format_select_option(code, description=’’)
return [code + (description.blank? ? ‘’ : ’ - ’ + description),
code]
end

Thanks.

Pepe

On Jul 15, 10:08 am, Matthew R. Jacobs <rails-mailing-l…@andreas-

pepe wrote:

Hello.

I have a piece of code (method) that I want all my models to have
available. What would be the best way to implement it?

Thanks

What sort of code is it?
Best way may be to extend ActiveRecord::Base

take a look at some plugins for examples.

eg. ActsAsSolr
http://github.com/thomas/acts_as_solr/tree/master/lib/acts_as_solr.rb

it defines a module;

module ActsAsSolr
module ActsMethods

stuff to extend ActiveRecord::Base

end
end
then does the extend.

reopen ActiveRecord and include the acts_as_solr method

ActiveRecord::Base.extend ActsAsSolr::ActsMethods

You’ll see the same quite a bit with a;

module BlahBlahBlah::InstanceMethods

end

ActiveRecord::Base.include(BlahBlahBlah::InstanceMethods)

just play around in console,
see what feels most comfortable.

Yes, it is something destined for the views. I was a little torn
because I didn’t want to put anything in the views or the models that
didn’t belong there. I just didn’t think about passing the result set
to a method from the view. You just gave me what I actually was
looking for from the beginning.

Thanks a lot!

Pepe

On Jul 15, 10:21Â am, Matthew R. Jacobs <rails-mailing-l…@andreas-

pepe wrote:

It’s just a piece of code to format data that will go in a
form.select. Something like this:

def format_select_option(code, description=’’)
return [code + (description.blank? ? ‘’ : ’ - ’ + description),
code]
end

Thanks.

Pepe

On Jul 15, 10:08�am, Matthew R. Jacobs <rails-mailing-l…@andreas-

ok,
so that’s something you just use in views…

so it should probably go in application_helper.rb

blah.erb.html

<%= select(:user, :countries, select_options(@all_countries)) %>

application_helper.rb

def select_options(records)
records.map do |record|
format_select_option(record.name, record.description)
end
end

def format_select_option(code, description=’’)
return [code + (description.blank? ? ‘’ : ’ - ’ + description),
code]
end

or something?

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