Display code block but also resolve variable within it - ruby-on-rails

Rails 7 / Ruby 3
I'm currently working on a site that requires code examples to be displayed on a page - I can get these to display utilising the extra % character trick, however, for some of the examples I need to have a variable within them that is resolved (e.g. like the users' own API key etc...).
Consider I have #variable = "Resolved Variable"
<%%= link_to #variable, variable_path %>
Outputs on the page explicitly as
<%= link_to #variable, variable_path %>
But I really need the #variable to resolve and show on the page as:
<%= link_to "Resolved Variable", variable_path %>
I've tried all kinds of escaping the variable, but it seems that <%%= ensures that nothing following it can be resolved.
Any ideas?

Any text you haven't html_encodeed will be displayed as plain text.
My suggestion to you is to create a interpolated string that you could use to generate your intended result. For example:
output_text = "<%= link_to '#{#variable}', variable_path %>"
And, not sure if this is what you're looking for, but you can get a good UI by adding some Javascript library to format you code in the language in intend (in this case Ruby, it seems).
In case that's interesting to you, check the Prism lib, or check how to add it to your project here
I hope this helps.
With kind regards,
Rogerio

<%% in ERB will simply output <%, no more, no less. In particular, it won't attempt to parse the code after <%% as Ruby. However, this doesn't mean that you can't have another <%= ... %> after <%%:
require 'erb'
template = <<-EOD
<%%= link_to <%= #variable.inspect %>, variable_path %>
EOD
#variable = "Resolved Variable"
puts ERB.new(template).result
The inspect method will add quotes around your string and also escape certain characters as needed.
Output:
<%= link_to "Resolved Variable", variable_path %>

Related

How to interpolate ruby inside of an interpolated bit of ruby in ERB

I'm trying to create a situation where one user makes message templates and another one can plug in values. I'm using the best_in_place gem, which will allow a user to edit the message on the show page.
The problem is this. When I call the message, with the required erb to make the gem work, it treats all of this as a regular string, not as ruby.
This is unclear, I'm sorry.
Here's the code.
#announcement.content = "The <%= best_in_place #announcement, :train %> is arriving in five minutes."
/show.html.erb
<%= #announcement.content %>
I want it to put "The click to set train is arriving in five minutes." and if the user clicks where it says "click to set train," a text field will open for them to edit (this is something the best-in-place gem does).
Instead, it puts "The <%= best_in_place #announcement, :train %> is arriving in five minutes."
I understand why it is doing this, but I don't know how to make it instead interpret the ruby I'm trying to pass in.
Ideas?
Use regular old string interpolation:
#announcement.content = "The #{best_in_place #announcement, :train} is arriving in five minutes."
You can use ERB to render any ERB template string. In this case something like:
<%= ERB.new(#announcement.content).result %>
Although you likely won't have access to all your Rails helpers, etc.
The Rails way to do this:
#announcement.content_type = :arriving
Later:
<%= render(partial: #announcement.content_type)
In _arriving.erb:
The <%= best_in_place #announcement, :train %> is arriving in five minutes.
TL;DR: ERB is not Ruby, and Rails uses both at different times.
You want simple Ruby string interpolation here:
#announcement.content = "The #{best_in_place #announcement, :train} is arriving in five minutes."
This is unclear, I'm sorry.
Not to worry, the Rails framework throws so many different new concepts at you it can be frustrating for newcomers.
Start from this: the Ruby framework builds the answer to the user's browser from a collection of resources Each file is evaluated by an interpreter for its own language. The trick is: look at the extension.
Files ending in .coffee will be compiled into javascript, files ending in .scss will become CSS, and in the same way files ending in .erb will yield HTML.
ERB is a language composed of mostly HTML already, plus a tag that allows you to interpolate Ruby. ERB stands for Embedded Ruby.
What about files ending in .rb, like the file in which you (surely) are evaluating #announcement.content = "The <%= best_in_place[...]" (a controller, I guess)?
Well, that's just pure Ruby :) that's why the ERB interpolation syntax <%= ... > is not recognized.
What you want to do in the controller, is (as you're trying to do) preparing the data for the view. The ruby in the <%= ... > tag in ERB will have access to the controller's instance variables, i.e. the variables with an # in front defined in the controller. But to define those, inside the controller, you should rely on Ruby alone.
Take-home message:
Be aware of which language you are writing in at each moment. For example:
# show.html.erb
<p>Here is ERB, which will be interpreted straight into HTML</p>
<% "Inside the '<% ...' tag is Ruby, but results won't show up in the HTML because there's no '<%='."%>
<% which_language = "Ruby" # Even variable assignments, and comments, do work %>
<%= "Inside the '<%=' tag, you're writing and interpolating #{which_language} :)" %>
I think the fact that I wasn't clear made it hard to answer this question.
What I'm doing is transforming user-inputted text (using a method in the model, called by the controller) to replace certain keywords with erb tags that call the best_in_place plugin. In my view, when presenting this content to another user, I wanted to call this content, which is saved as an attribute in the database, in such a way that it would render correctly for the other user to have the best_in_place functionality active.
Here's what I ended up doing. It is working, but if you have better ideas, please let me know.
In the announcements#create view, the user creates an announcement with certain pre-defined blocks of bracketed text as well as free-input text. For example, they might write "[train] is leaving from [platform] in [time] minutes."
When they hit save, the controller's create action calls the construct_message method from the model. It looks like this:
def construct_message(msg)
msg.gsub! '[train]', '<%= best_in_place #announcement, :train_id, :as => :select, collection: Train::list_trains, place_holder: "Click here to set train." %>' #note: list_trains and list_platforms are methods on the model, not really important...
msg.gsub! '[platform]', '<%= best_in_place #announcement, :platform_id, :as => select, collection: Platform::list_platforms, placeholder: "Click here to set platform." %>'
msg.gsub! '[time]', '<%= best_in_place #announcement, :number_of_minutes, placeholder: "Click here to set." %>'
end
Then, when I want to show that attribute in my view, I'm using render :inline, like this.
on announcements/:id
<p id="notice"><%= notice %></p>
<p>
<strong>Content:</strong>
<% announcement = #announcement %>
<%= render :inline => announcement.content, locals: { :announcement => announcement } %>
</p>
This allows the erb call that I wrote into the attribute to be functional.
Also note that I'm choosing to use a local rather than instance variable here; this is because in announcements#index, I also render this text and the table there uses local variables.

Is there a way of just having one pair of <% %> in ruby on rails [duplicate]

Sometimes it's more convenient to print in <%%>. How to do it in Rails?
http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-concat
Should be what you are looking for.
E.g. the following statement using concat:
<% concat "Output" %>
is equivalent to:
<%= "Output" %>
In ERB:
The <% %> signify that there is Ruby code here to be interpreted.
The <%= %> says output the ruby code, ie display/print the result.
So it seems you need to use the extra = sign if you want to output in a standard ERB file.
Otherwise, you could look at alternatives to ERB which require less syntax,.. maybe try something like HAML. http://haml-lang.com/tutorial.html
Example:
# ERB
<strong><%= item.title %></strong>
# HAML
%strong= item.title
Is that more convenient?
erb has two method to evaluate inline ruby expressions. The <% which evaluates the expression and the <%= which evaluates and prints. There is no global object to print to within the binding context.
As mentioned by Omar, there is a concat method, which is part of ActionView. This will do what you want.
Unlike a scripting language escape, there is no default output for erb. Since erb is simply a function, and given a template and binding will return a variable, it returns the values of text and functions recursively.
There is hot debate as to how much logic should be allowed in a view, but as little as possible is what most people aim for. If you are putting more code than text in the view, you may want to consider refactoring your code.

Variable + HTML to Button + Ruby on Rails views

I am having a an issue.
<%= link_to "<button>Add</button>".html_safe, new_admin_course_path, :id=>"open-contacts-dialog-btn", :class=>"inbox-sf-add-btn tip" %>
What if I want to add a ruby variable and some normal text the button? e.g. $25,- (where the $ and ,- are fixed and the 25 variable...I am quite new to this...sorry if this is too easy, but struggling. I tried a lot of options and googled for long time.
The correct helper you want for this is button_to.
To use a variable in the button text is defined as string iterpolation. In your example it could be something like:
<%= button_to "$#{cost}", new_admin_course_path %>
Check out the button_to api reference for more options.
you could do like
amount = 25 #amount is the ruby variable
<%= link_to "<button>Add $#{amount}</button>".html_safe, new_admin_course_path, :id=>"open-contacts-dialog-btn", :class=>"inbox-sf-add-btn tip" %>
and I personally dont add <button></button> to the link and I rather use CSS to get the look and feel
Put your link inside a <button></button> tag. It'll be more readable.
And use variables interpolation in double-quoted strings to insert variable's value into string (the #{#variable_name} part)
<button>
<%= link_to "$#{variable_name}", new_admin_course_path, :id=>"open-contacts-dialog-btn", :class=>"inbox-sf-add-btn tip" %>
</button>

Why use <%Q in rails 3

I've noticed that all of the rails APIs seem to use either of the following two notations for code nuggets in erb files;
<%Q ... %>
<%= ... %>
But seldom any mention of the vanilla
<% %>
for example, here;
http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html
The book I've just read didn't cover the <%Q notation, so I'm assuming it's new. Is there any significance to the "Q" or is this just best practice now instead of just using <% ?
<% %> and <%= %> are features of erb. <% %> is used to embed some code in a template e.g. it would be used to embed an if statement
<% if #person.age > 18 %>
<%= %> is used to output a value within the template e.g
Name: <%= #person.name %>
%Q is a feature of the Ruby language and is not a Rails specific thing. As johnernaut writes it is used for double-quoted strings. e.g. instead of puts "Say \"Hello\"" where you need to escape the double-quotes you can write puts %Q(Say "Hello")
However the %Q you're seeing in some of the Rails documentation don't seem to be a use of this Ruby feature. If you look at the actual source of form_helper.rb it doesn't have them so I'm thinking it's a quirk of the rdoc documentation tool.
Update: As Frederick as posted whilst I was writing the above, it looks like it is an rdoc bug.
<% %> and <%= %> seem to be the common standard. I believe %Q is used for double quoted strings:
>> %Q(Joe said: "Frank said: "#{what_frank_said}"")
=> "Joe said: "Frank said: "Hello!"""
Found via relevant link.
The <%Q in the docs is the result of a bug in the rdoc tools being used, see this thread

Print in ERB without <%=?

Sometimes it's more convenient to print in <%%>. How to do it in Rails?
http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-concat
Should be what you are looking for.
E.g. the following statement using concat:
<% concat "Output" %>
is equivalent to:
<%= "Output" %>
In ERB:
The <% %> signify that there is Ruby code here to be interpreted.
The <%= %> says output the ruby code, ie display/print the result.
So it seems you need to use the extra = sign if you want to output in a standard ERB file.
Otherwise, you could look at alternatives to ERB which require less syntax,.. maybe try something like HAML. http://haml-lang.com/tutorial.html
Example:
# ERB
<strong><%= item.title %></strong>
# HAML
%strong= item.title
Is that more convenient?
erb has two method to evaluate inline ruby expressions. The <% which evaluates the expression and the <%= which evaluates and prints. There is no global object to print to within the binding context.
As mentioned by Omar, there is a concat method, which is part of ActionView. This will do what you want.
Unlike a scripting language escape, there is no default output for erb. Since erb is simply a function, and given a template and binding will return a variable, it returns the values of text and functions recursively.
There is hot debate as to how much logic should be allowed in a view, but as little as possible is what most people aim for. If you are putting more code than text in the view, you may want to consider refactoring your code.

Resources