4

I have an Adult model with a name attribute.

If the user is logged in, I want the Adult.name to only return the first name.

Is there a way to have helpers tied to a model where you could specify Adult.helper.name?

Or a least have helpers namespaced to a model?

Christopher
  • 3,391
  • 2
  • 21
  • 13

2 Answers2

11

Just explicitly include the helper in your model

# app/helpers/adults_helper.rb
module AdultsHelper
  def say_hello
    "hello, world!"
  end
end

# app/models/adult.rb
class Adult < ActiveRecord::Base
  include AdultsHelper

end

Test in console

$ script/console
>> a = Adult.new
# => #<Adult id:...>
>> a.say_hello
# => "hello, world!"
maček
  • 76,434
  • 37
  • 167
  • 198
  • interesting, I like this approach. I may have to think of the best way to name it... maybe Adult.public_name ? – Christopher Apr 25 '10 at 06:48
  • this does create a problem when I try to generate links in the helper since I get the error: "undefined method `polymorphic_path" – Christopher Apr 25 '10 at 07:37
2

in your Adult model you can add

def name
  self.first_name
end

so when you find an Adult, like

a = Adult.last
puts a.name #will print a.first_name

Well, for a better explanation.. paste some code!

amrnt
  • 1,331
  • 13
  • 30
  • the trouble with this is that if I wanted to display the whole name or first name based on whether the user was logged in (authlogic) I would need to add that condition in every instance where I pulled the user's name – Christopher Apr 25 '10 at 06:46