Answer the question
In order to leave comments, you need to log in
Self-written rails. How to execute a method inside a view?
Hello. I'm trying to make my own MVC framework similar to rails, I need it for self-development. I implemented the base controller and for each view controller, everything is the same as in rails. I did a job with the general template through yield, but I can't figure out how to pass the method inside the template? For example, I have a main template and everything is divided into blocks, let's say the block <%= render : head %> below is yield to insert a template based on the name of the controller and action.
So far done like this:
require 'erubis'
module LiveQueue
class Controller
def render(views_action, options = {})
template = File.read(File.join('app', 'views', controller_name, "#{views_action}.html.erb"))
Erubis::Eruby.new(template).result(options)
end
def default_template(&block)
template = File.read(File.join('public', 'application.html.erb'))
Erubis::Eruby.new(template).evaluate(&block)
end
def render_layout(name)
template = File.read(File.join('app', 'views', 'layouts', "_#{name}.html.erb"))
end
private
def controller_name
self.class.to_s.gsub(/Controller$/, "").downcase
end
end
end
class AdminController < LiveQueue::Controller
def index
default_template { render(:index, name: 'Евгений', last_name: 'Кунгуров') }
end
end
template = "привет <%= render %>"
def render; 'еще раз привет'; end
Erubis::Eruby.new(template).evaluate { render }
Так метод передается.
def default_template(&block)
template = File.read(File.join('public', 'application.html.erb'))
Erubis::Eruby.new(template).evaluate(&block) { метод, который надо передать }
end
Answer the question
In order to leave comments, you need to log in
In general, I solved the problem, as I guessed, I extended the Context class of the Erubis module.
When we do Erubis::Eruby.new(template).evaluate, the evaluate method creates an instance of Context.new, and since I extended it with my own methods, everything worked
module Erubis
class Context
include MyHelpers
end
end
but I can't figure out how to pass the method inside the template?
I'll give my opinion, nothing more.
Man you are great. This is a very cool practice. Everyone should write their own great to understand how the language works, how frames work.
BUT:
if they start dismantling "your rails" for you, then nothing good will come of it.
Tip:
Try each stage of the logic to check and go through all the files. Also, each link was googled on the docks and figured out how it should work.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question