Create your own tags/functions with Erubis - ruby

I have a ruby class that extends Erubis (a ruby templating engine) and I would like to create my own tags. The following is an example of what i'd like to be reproduce:
<%= link_to "/some/url" %>
This code should generate a html 'a' tag linking to some url. Now i'd like to be able to create my own tags such as:
<%= javascript_file "/some/javascript/file" %>
which would generate a script tag linking to some javascript file of my choice.
How can i easily extend erubis to do that?
Thanks for your time.

Those are just function calls that return the tag in a string:
def javascript_file( file_path )
"<script src=\"#{ file_path }\" type=\"text/javascript\"/>"
end
You just need to ensure that the functions are within scope at the time you call the binding.

Related

How to add img tags to button text using haml and erb button_to helper function

I have this piece of code (ruby haml)
= button_to tr('single_sign_on') , '/something/something0', method: :post, class: "btn-SSO"
Now I need to insert 2 icons to the button text.
Any idea how to do that. I have zero experience with this tech & codebase.
This doesn't have to use the button_to helper function.
Can be just plain haml (i'm assuming I would have to wrap this in a form then).
This helper takes a block as a parameter where you can add icons https://apidock.com/rails/v5.2.3/ActionView/Helpers/UrlHelper/button_to
= button_to '/something/something0', method: :post, class: "btn-SSO" do
= tr('single_sign_on')
i.fa.fa-save # example

How to render a value from an .rb file into an .erb file

I don't have much experience with Ruby all I wan't to do is render a value that I declare in an .rb file in an .erb file.
In my .rb file I have this:
def abc()
begin
"aaaaa"
end
end
In my .erb file I have this:
Hello <% abc %>
When I run the app I only see:
Hello
But I expect to see:
Hello aaaa
Anybody can give me a hand, I don't really know ruby at all. Also I have no idea if this is ruby or ruby on rails so sorry if the tag below is wrong.
In Sinatra, register your method as a helper in .rb file:
helpers do
def abc
"aaaaa"
end
end
Omit parentheses if your methods don't need arguments. Also, begin/end block isn't necessary here.
You can call your helper in .erb template:
<%= abc %>
Don't forget = in the opening tag.
http://sinatrarb.com/intro.html section 'Helpers'.
It's unclear what you want to achieve. But If you just want some text in your erb you can do something like this:
erb :myerb, locals: {text: "aaaaa", saved: false}
myerb.erb
<% if saved %>
Hello <%= text %>
<% endif %>
This would also work for functions.
First of all, you need to be aware that a defined method inherently includes the functionality of a begin/end block so you don´t need to put them again. Assuming you are using sinatra, here is what I think you need:
my.rb
require 'sinatra'
def abc
"aaaa"
end
get '/' do
erb :my, locals: {variable: abc}
end
my.erb
<html>
<body>
<p>
Hello <%= variable %>
</p>
</body>
</html>
Run ruby my.rb and then open http://localhost:4567/

How to render erubi template to html?

As rails 5.1+ switched to erubi I tried to use that in ruby script:
require 'erubi'
template = Erubi::Engine.new("<%= test %>", escape: true)
However I'm stacked trying to render that template to html.
erubi source code: https://github.com/jeremyevans/erubi
erubi is fork of erubis, and in erubis the rendering is done via result method:
require 'erubis'
template = Erubis::Eruby.new("<%= test %>", escape: true)
template.result test: "<br>here" #=> "<br>here"
However there's no result method in erubi.
From the Erubi README (it says “for a file” but it appears to mean “for a template”):
Erubi only has built in support for retrieving the generated source for a file:
require 'erubi'
eval(Erubi::Engine.new(File.read('filename.erb')).src)
So you will need to use one of the eval variants to run from a standalone script.
template = Erubi::Engine.new("7 + 7 = <%= 7 + 7 %>")
puts eval(template.src)
Outputs 7 + 7 = 14.
If you want to be able to use instance variables in your template as you might be used to from Rails, Sinatra etc., you will need to create a context object and use instance_eval:
class Context
attr_accessor :message
end
template = Erubi::Engine.new("Message is: <%= #message %>")
context = Context.new
context.message = "Hello"
puts context.instance_eval(template.src)
Outputs Message is: Hello.
In rails 5.1 I switched out the Erubis::Eruby.new code to the following:
ActionController::Base.render(inline: "<%= test %>", locals: {test: "<br>here"})
Rails will do the heavy lifting.

How to implement form_tag helpers without actionview?

I'm working on a Sinatra app and want to write my own form helpers. In my erb file I want to use the rails 2.3 style syntax and pass a block to a form_helper method:
<% form_helper 'action' do |f| %>
<%= f.label 'name' %>
<%= f.field 'name' %>
<%= f.button 'name' %>
<% end %>
Then in my simplified form helper I can create a FormBuilder class and yield the methods to the erb block like so:
module ViewHelpers
class FormBuilder
def label(name)
name
end
def field(name)
name
end
def button(name)
name
end
end
def form_helper(action)
form = FormBuilder.new
yield(form)
end
end
What I don't understand is how to output the surrounding <form></form> tags. Is there a way to append text on only the first and last <%= f.___ %> tags?
Rails has had to use some tricks in order to get block helpers to work as wanted, and they changed moving from Rails 2 to Rails 3 (see the blogposts Simplifying Rails Block Helpers and Block Helpers in Rails 3 for more info).
The form_for helper in Rails 2.3 works by directly writing to the output buffer from the method, using the Rails concat method. In order to do something similar in Sinatra, you’ll need to find a way of writing to the output from your helper in the same way.
Erb works by creating Ruby code that builds up the output in a variable. It also allows you to set the name of this variable, by default it is _erbout (or _buf in Erubis). If you change this to be an instance variable rather than a local variable (i.e. provide a variable name that starts with #) you can access it from helpers. (Rails uses the name #output_buffer).
Sinatra uses Tilt for rendering templates, and Tilt provides an :outvar option for setting the variable name in Erb or Erubis templates.
Here’s an example of how this would work:
# set the name of the output variable
set :erb, :outvar => '#output_buffer'
helpers do
def form_helper
# use the new name to write directly to the output buffer
#output_buffer << "<form>\n"
# yield to the block (this is a simplified example, you'll want
# to yield your FormBuilder object here)
yield
# after the block has returned, write any closing text
#output_buffer << "</form>\n"
end
end
With this (fairly simple) example, an Erb template like this:
<% form_helper do %>
... call other methods here
<% end %>
results in the generated HTML:
<form>
... call other methods here
</form>

What would the erb template look like for a ruby enumerator?

What would the erb template look like for a ruby enumerator? The answer will be a erb template.
require "erb"
# build data class
class Foo < Array
def build
b = binding
# create and run templates, filling member data variables
ERB.new(File.read('test2.erb')).result b
end
end
# setup template data
bar = Foo.new([1,2,3])
puts bar.build
I would like some way of accessing the 1,2,3 items in the erb template.
Focus on Ruby 1.9.3 compatibility.
Note: the Class is an extension of Array, and I want to access the elements of this array in its erb template.
Ok, it was as simple as reaching into the self reference.
<% self.each{|element| %> <%= element %> <% } %>

Resources