JapanGuy JapanGuy - 1 year ago 57
Ruby Question

rails method as a function

This has probably been asked before but I cannot find any info on this

I am using I18n with 2 locales en and ja

Trying to fetch data from a table that has columns like title_en title_jp. So when locale is en title_en should be shown

Is there a short way to do this in ruby?

I am trying to use helpers:

module WorksHelper
def col_lang(col)
if (locale == :ja)
lang = "_ja"
lang = "_en"
return col+lang

And then I cant figure out a way to call this in the views. I am trying this:

<%= work.(col_lang("title")) %>

but obviously this is wrong. Ruby says
undefined method call
. How do I call the function here?

Answer Source

Change the line in the view to:

<%= work.send(col_lang("title")) %>

Or (because IMO it is easier to read) change the helper to:

module WorksHelper
  def localized_attribute(instance, attribute)
    suffix = (locale == :ja) ? 'ja' : 'en'

and call it in your view like this:

<%= localized_attribute(work, :title) %>