Search code examples
ruby-on-railsrubyruby-on-rails-4ajaxify

Call Rails helper in every view impliedly as first argument


I have a Rail 4 application that uses the ajaxify_rails Gem. So only my content is loaded but not the full page. Now I have defined a helper method that I want to call in every view as first statement. My current approch is doing this explicit in every view, but this is much duplicated code. So I have many views all starting with

= rails_helper_method
...

Is there a way to to this impliedly on every view, or do I just have to call it over and over again?


Solution

  • This is what layouts are for. Just call your helper method in your layout and since your views will use that layout so your helper method will also get called up. In your layout file you can do:

    %body
      = rails_helper_method
      = yield
    

    Update:

    If you look at ajaxify_rails repo, you can call its ajaxify_extra_content method in application_controller and then bind it to ajaxify event. You can do something like this:

    def ajaxify_extra_content
      ... your extra html ...
    end
    

    and then bind it like this:

    $(document).on 'ajaxify:content_inserted', ->
      $('#id_of_some_container_in_view').html $('#ajaxify_content #id_of_some_container_in_view').html()
    

    you can also call your helpers directly like this:

    def ajaxify_extra_content
      view_context.your_helper
    end
    

    PS I haven't tested it but this should work for you