Chris Yeung
Chris Yeung

Reputation: 2723

Rails create a helper to add text

I have a fee column in my model and it is an integer type, so I try to create a tiny helper to add a dollar sign neatly in front. Which means, instead of writing:

span = "$#{@object.fee}"

I can write something like

span = @object.fee.dollar

So I created the tiny helper.

module ApplicationHelper
    def self.dollar
        "$#{self.try(:to_s)}"
    end
end

I am not sure where to put it, so basically it's now showing

undefined method `dollar' for 180:Fixnum

Upvotes: 0

Views: 270

Answers (4)

Elvn
Elvn

Reputation: 3057

number_to_currency()

Rails 4.2 has this ActionView::Helper

number_to_currency(1234567890.506)

Helper

If you want to implement this as a helper, this works

module ApplicationHelper
    def dollar(amount)
       amount = number_to_currency(amount)
    end
end

Invoke

<%= dollar(your_var_here) %>    

Rails spec for number_to_currency()

http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_currency


Note: Other versions of Rails may have this function, you'd have to check your version.

Upvotes: 2

Kristj&#225;n
Kristj&#225;n

Reputation: 18803

Your helpers are included in the view context, so you need two changes:

  1. def dollar - because it's included in the renderer, you don't need self
  2. Call it as dollar(@object.fee) - it's not included on the object, but in your view. If you want to call it as @object.dollar, declare the method in whatever class @object is.

Additionally, the number_to_currency helper already exists and is quite robust. Perhaps you want to use that.

Upvotes: 0

disastrous-charly
disastrous-charly

Reputation: 1085

I think it's because you're in a helper, so you can't refer to self.

You can do it in your Model, or in the helper do : def print_dollar(your_value)

Or, you can also use : number_to_currency(dollar, :unit => "$"), which will render it the way you want.

Hope it help

Upvotes: 0

AbM
AbM

Reputation: 7779

module ApplicationHelper
    def dollar(amount)
        "$#{amount}"
    end
end

and then:

span = dollar @object.fee

Upvotes: 0

Related Questions