简体   繁体   中英

How to include my own Ruby (on rails) functions inside an HTML page

I'm creating a web-app. While it works great, writing whole pieces of code inside "<% %>" tags in ruby on rails is pretty ugly.

I tried to define a function in my controller.rb and then call it from the html page. This does not work, as it does not recognize the function.

I'd appreciate any help here. Did I put my function in the correct place? Do I need to load using "require"?

For example:

controller file:

class WelcomeController < ApplicationController
 def index
 end
 def myfunc(x)
  puts x
 end
end

HTML file (index.html):

<h1>Welcome</h1>
<p>
<%= myfunc(5) %>
</p>

What you are referring to is called a helper in Rails. There are two ways that you could implement this.

Option number one is to place the method you want to access inside a helper module. The most common one is ApplicationHelper which you can find in RAILS_ROOT/app/helpers/application_helper.rb . If you place the method in there it will be accessible from the views.

Another way if you still want/need to have the method in the controller, then you can use the helper_method function like this:

def WelcomeController < ApplicationController
  helper_method :my_func

private
  def my_func(x)
    puts x
  end
end

The usage of private is not needed, but only good practice so that the method cannot be accidentally used as a Controller action or something.

Ruby on rails has a Model-View-Controller architecture - in those architectures you can't access the controller from the view.

You could set a variable with the output from your function, and access that variable from your view

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM