Rails: Create method available in all views and all models

Posted by smotchkkiss on Stack Overflow See other posts from Stack Overflow or by smotchkkiss
Published on 2010-03-18T01:00:46Z Indexed on 2010/03/18 2:51 UTC
Read the original article Hit count: 402

I'd like to define a method that is available in both my views and my models

Say I have a view helper:

def foo(s)
  "hello #{s}"
end

A view might use the helper like this:

<div class="data"><%= foo(@user.name) %></div>

However, this <div> will be updated with a repeating ajax call. I'm using a to_json call in a controller returns data like so:

render :text => @item.to_json(:only => [...], :methods => [:foo])

This means, that I have to have foo defined in my Item model as well:

class Item
  def foo
    "hello #{name}"
  end
end

It'd be nice if I could have a DRY method that could be shared in both my views and my models.

Usage might look like this:

Helper

def say_hello(s)
  "hello #{s}"
end

User.rb model

def foo
  say_hello(name)
end

Item.rb model

def foo
  say_hello(label)
end

View

<div class="data"><%= item.foo %></div>

Controller

def observe
  @items = item.find(...)
  render :text => @items.to_json(:only=>[...], :methods=>[:foo])
end

IF I'M DUMB,

please let me know.

I don't know the best way to handle this, but I don't want to completely go against best-practices here.

If you can think of a better way, I'm eager to learn!

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about best-practices