Sash
Sash

Reputation: 4598

Rails using ActionView::Helper methods outside of view

I've created a helper which I'd like to use for text manipulation

module ApplicationHelper

  module TextHelper

    extend ActionView::Helpers

  end
end

However when I run ApplicationHelper::TextHelper.simple_format "foo" in Rails console I get

NoMethodError: undefined method `white_list_sanitizer' for Module:Class

Is there anything else I need included?

I have already looked at https://github.com/rails/rails/issues/13837 but it didn't work.

Using Rails 4, Ruby 1.9.3

Upvotes: 1

Views: 3537

Answers (2)

mechnicov
mechnicov

Reputation: 15248

It is possible to use helpers with ActionController::Base.helpers or (and) with Rails.application.routes.url_helpers

For example

helpers = ActionController::Base.helpers
url_helpers = Rails.application.routes.url_helpers

helpers.link_to "Root_path", url_helpers.root_path
# => "<a href=\"/\">Root_path</a>"

Upvotes: 1

jeremywoertink
jeremywoertink

Reputation: 2341

If you're in the console, you should be able to just do helper.simple_format('hi'). The helper method is available in console as a way to call some helper methods.

When using a custom helper:

# app/helpers/custom_helper.rb
module CustomHelper
  def custom_method(x)
    puts "Custom method #{x}"
  end
end

# from the console
helper.custom_method('hi')

# from the controller
class SomeController < ApplicationController

  def index
    view_context.custom_method('hi')
  end
end

Upvotes: 6

Related Questions