Nodir Rashidov
Nodir Rashidov

Reputation: 732

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_ja. 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"
        else
            lang = "_en"
        end
        return col+lang
    end
end

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?

Upvotes: 0

Views: 108

Answers (3)

ArtOfCode
ArtOfCode

Reputation: 5712

Effectively, what you're trying to do is to fetch a model's attribute by a string containing its name, rather than the symbol representation.

This is how you do that.

Ideally, you should avoid using send, as spickermann's answer recommends, because send will also let you send a destroy command without realising it. Not ideal. Try using read_attribute instead:

module WorksHelper
  def localized_attribute(instance, attribute)
    suffix = (locale == :ja) ? 'ja' : 'en'
    instance.read_attribute("#{attribute}_#{suffix}")
  end
end

Upvotes: 1

Stefan
Stefan

Reputation: 114138

Another approach is to define a method in your model:

class Work < ApplicationRecord
  # ...

  def title(locale = I18n.locale)
    public_send(:"title_#{locale}")
  end
end

And call it via:

<%= work.title %>

or, to specify a locale explicitly:

<%= work.title(:ja) %>

Upvotes: 2

spickermann
spickermann

Reputation: 106782

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'
    instance.send("#{attribute}_#{suffix}")
  end
end

and call it in your view like this:

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

Upvotes: 3

Related Questions