\" tags in ruby on rails is pretty ugly." />
开发者

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

开发者 https://www.devze.com 2023-04-11 07:46 出处:网络
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'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 i开发者_StackOverflow社区t 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

0

精彩评论

暂无评论...
验证码 换一张
取 消