I'm using rails 4.2.5.
And in rails API (for v4.2.5.2) I see this helper:
number_to_delimited(number, options = {})
Formats a number with grouped thousands using delimiter (e.g., 12,324). You can customize the format in the options hash.
http://api.rubyonrails.org/classes/ActiveSupport/NumberHelper.html#method-i-number_to_delimited
But when I using this help in my views, it throws an error:
undefined methodnumber_to_delimited' for #<#:0x0000000b091b30>`
Other helpers, such like number_to_currency, all works well. What's wrong with me?
Try to call ActiveSupport::NumberHelper instead.
ActiveSupport::NumberHelper.number_to_delimited(12345678)
=> "12,345,678"
Or you could do also with this:
include ActiveSupport::NumberHelper
number_to_delimited(12345678)
=> "12,345,678"
UPDATE:
I see you said in comment above that you're using haml code and you can do it like:
= ActiveSupport::NumberHelper.number_to_delimited(12345678)
Or
- include ActiveSupport::NumberHelper
= number_to_delimited(12345678)
Just include the ActiveSupport::NumberHelper in the ApplicationHelper.
module ApplicationHelper
include ActiveSupport::NumberHelper
end
Then you can directly use all the number helpers in your views.
<%= number_to_delimited(12345678) %>
number_to_delimited is a method in ActiveSupport::NumberHelper which cannot be used in the view directly.
Rails provides a couple of number helpers in ActionView::Helpers::NumberHelper which are delegated the methods in ActiveSupport::NumberHelper.
number_to_currency
number_to_human
number_to_human_size
number_to_percentage
number_to_phone
number_with_delimiter
number_with_precision
For example, if you want to delimit the number, you should call number_with_delimiter instead, which will call number_to_delimited in the ActiveSupport::NumberHelper.
# File actionview/lib/action_view/helpers/number_helper.rb, line 244
def number_with_delimiter(number, options = {})
delegate_number_helper_method(:number_to_delimited, number, options)
end
Hope that make sense. Cheers.
Related
When I put this in the application_helper.rb, it is available to use in the view
def foo
"bar"
end
But when I put this in application_helper.rb it is not available to use in the view (instead: NoMethodError undefined method)
def nice_datetime
self.strftime('%d %b %-I:%M%p %Z')
end
Why is the first method available in the view and the second method not available in the view?
The self part is the problem, it is referencing the view itself* and that doesn't have a method called strftime. You can fix it somewhat by doing
def nice_datetime(date)
date.strftime('...')
end
I would however urge you to look into localization.
Which would work something like this, just a very basic setup.
# config/locales/en.yml
en:
time:
formats:
short: "%H:%M"
<p><%= l Time.now, format: :short %></p>
* That might not be strictly true, I can't remember exactly how helpers are included in the view files, but for sake of this argument is close enough.
I have a helper with a method named search_form like this:
module Admin::BaseHelper
def search_form(*args)
# my great code here
end
end
To call this method in my HAML code, I can do this:
= search_form
= search_form()
= search_form(param1: "value1", param2: "value2"...)
My problem is with this first call. When I do this in any HAML file, it renders my helper. Except if my file name is _search_form.html.haml. Is that case, it returns nil.
If I put a raise error in the helper, I notice that my method isn't being called, but I am not able to find what is being called and why.
If I use the syntax on the second and third lines, it works as expected by calling my helper method.
So my question is: is this standard Rails behavior or a bug?
By default, Rails will look for a local variable with the same name as your partial, which may conflict with existing method names.
One way to get around this is to simply redefine the method inside your partial:
<% search_form = self.search_form %>
# Rest of the partial's code
I have a helper module for my home page with two methods that do the same thing:
module HomeHelper
def parsed_text(tweet)
auto_link (tweet).gsub(/(#\w+)/, %Q{\\1})
end
def other_parsed_text
self.auto_link.gsub(/(#\w+)/, %Q{\\1})
end
end
In my view this works:
<%= parsed_text(tweet.text) %>
But this doesn't:
<%= tweet.text.other_parsed_text %>
I get a NoMethodError at /
undefined method other_parsed_text. Isn't self the caller of the method inside of my helper method?
What am I doing wrong? I want the second style of calling methods with a . notation to work too. How do I do that?
This does not work because you didnt extend the class that tweet.text is of. You can use ActiveSupport::Concern if you want to extend some class. What you are doing now is provding some methods that can be called with parameters.
// I posted an example here: https://stackoverflow.com/a/8504448/1001324
Question has many Comments.
A URL "questions/123" shows a question.
A URL:
"questions/123#answer-345"
shows a question and highlights an answer. 345 - is id of Answer model, "answer-345" is id attribute of HTML element.
I need to override "answer_path(a)" method to get
"questions/123#answer-345"
instead of
"answers/345"
How to do it ?
All url and path helper methods accept optional arguments.
What you're looking for is the anchor argument:
question_path(123, :anchor => "answer-345")
It's documented in the URLHelper#link_to examples.
Using this argument, you should be able to create an answer_path helper via:
module ApplicationHelper
def answer_path(answer)
question_path(answer.question, :anchor => "answer-#{answer.id}")
end
end
Offering a solution which covers more areas (works not only in views but also in controller/console)
module CustomUrlHelper
def answer_path(answer, options = {})
options.merge!(anchor: "answer-#{answer.id}")
question_path(answer.question, options)
end
end
# Works at Rails 4.2.6, for earliers versions see http://stackoverflow.com/a/31957323/474597
Rails.application.routes.named_routes.url_helpers_module.send(:include, CustomUrlHelper)
This seems like a noob question, but the simple answer is eluding me. I need to call link_to in an ActionController method to spit out an HTML link. ActionView::Helpers::UrlHelper.link_to calls url_for, but this calls the AV module's version instead of the controller's. I managed to coerce this into doing what I intended by putting
#FIXME there must be a better way to mixin link_to
alias_method :self_url_for, :url_for
include ActionView::Helpers::UrlHelper
alias_method :url_for, :self_url_for
in the controller. But, I'm still not sure why it works exactly. Could someone please explain the method scope and hiding that's happening here? What's a better way to mix in link_to (or generally, to include only some methods from a module) so I can call it in the controller (generating a flash string with a link is the use case.)
Please, no lectures about MVC--if anything, link_to should be in a module separate from url_for. Judging from the amount of noise on this, lots of people run into this seemingly trivial snag and end up wasting an hour doing it the "Rails way" when really what is wanted is a one minute hack to make my app work now. Is there a "Rails way" to do this with helpers perhaps? Or a better ruby way?
Compatible with Rails 3,4 and 5:
view_context.link_to
This doesn't really answer your question but there is an easier way
For Rails 5, use the helpers proxy
helpers.link_to '...', '...'
For Rails 3 and 4, since you are using the helper from a controller you can use the view_context
# in the controller code
view_context.link_to '...', '...'
# instead of using your mixin code
link_to '...', '...'
For Rails 2, since you are using the helper from a controller you can actually access the #template member variable of the controller, the #template is the view and already has the UrlHelper mixed in
# in the controller code
#template.link_to '...', '...'
# instead of using your mixin code
link_to '...', '...'
if you need to use the urlhelper from code other than the controller, your solution is probably the way to go
I still had problems using my own helper methods that use built-in helper methods in a controller with ActionController.helper.my_method.
Obviously using render_to_string for each flash would work, but I don't want to create so many small partials for each flash.
My solution was to create a little helper for controllers to execute code in a partial.
The helper method in the controller:
def h(&block)
render_to_string(:partial => 'helper', :locals => {:block => block})
end
The HAML partial (helper.html.haml):
= instance_eval &block
Same would work in ERB (helper.html.erb):
<%= instance_eval &block %>
Use it like this in your controller to call the my_custom_helper_function that's defined in a helper:
redirect_to url, :notice => h{my_custom_helper_function}
You can do it like this:
ActionController.helpers.link_to("Click Me!", awesome_path)
But really, a better place to generate that link might be in a helper module where UrlHelper and other view-related helpers are already included.
[update]
This approach is outdated and no longer works.