Search code examples
ruby-on-railsruby-on-rails-3best-in-place

How do I call a number_helper in my model?


I am using best_in_place gem, and to cut a long story short I can't call this particular helper in my view, because I have to call a custom method in my model to customize how I want the output to look.

This is the call in my view:

<td><%= best_in_place firm, :size, :type => :input, :nil => "Click to add Firm Size", :display_as => :in_millions %></td>

This is the method in my Firm model:

def in_millions
    "$#{self.size}M"
end

The numbers entered by the user won't be 100000000, but rather 100. So I want to take that 100 and have it just read $100M. That's what my helper does.

But, for those numbers that are like 12345, I want the output to look like this: $12,345M.

The easiest way I can think is just to add number_with_delimiter(self.size) and keep the $ and M, but I can't access that helper method from my model.

Thoughts?


Solution

  • You can include helpers in your model by including ActionView::Helpers:

    # in model
    include ActionView::Helpers
    

    I wonder, though, if it wouldn't make better sense to keep the presentation on the presentation side. You could just wrap up the extra logic in an alternative helper instead:

    # in helper
    def firm_size_in_millions(firm)
      size = number_with_delimiter(firm.size)
      "$#{size}M"
    end
    
    <!-- in view -->
    <%= firm_size_in_millions(@firm) %>