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.
I happen to be passing a url within the message body in my model_class. The link renders out well in views but it is unclickable (as a user has to manually copy it). Below is how i am passing the link in model class.
class Something < ActiveRecord::Base
messsage_body = "Hi! Follow this link to say hi! #{Rails.application.routes.url_helpers.user_say_hi_url(#user, :host => "localhost:3000")
end
Try calling it in my view with following:
<%= #something.message_body.html_safe %>
<%= raw #something.message_body %>
<%= h #something.message_body %>
And the link still remains un-clickable.
Hope mt explanation was clear enough thanks...
The link is unclickable because you are not actually making it a link using rails' link_to helpers or creating a HTML anchor tag manually or any other method. You are just printing out a URL.
I've a text attribute for a model named :settore_scientifico_progetto and three string attributes, :macrocat, :cat, :microcat:
class Modulo1 < ActiveRecord::Base
before_create :set_settore_scientifico_progetto
before_update :update_settore_scientifico_progetto
private
def set_settore_scientifico_progetto
self.settore_scientifico_progetto = "#{macrocat}\n#{cat}\n#{microcat}"
end
def update_settore_scientifico_progetto
self.settore_scientifico_progetto = "#{macrocat}\n#{cat}\n#{microcat}"
end
I'd like to put a new line where I typed \n but the code I posted gives me the output
macrocat cat microcat.
I would like it as follows:
macrocat
cat
microcat
The output is shown in show.html.erb:
<div class="form-field">
<h3>Settore scientifico:</h3>
<p><%= #modulo1.settore_scientifico_progetto %></p>
</div>
Rails has a helper specifically for this purpose called simple_format.
<%= simple_format #modulo1.settore_scientifico_progetto %>
This will output the following HTML:
<p>macrocat<br/>
cat<br/>
microcat
</p>
Which is rendered by your browser like this:
macrocat
cat
microcat
That seems to be exactly what you're looking for, and it takes care of sanitizing your HTML for you. (Options for customizing the output, e.g. changing the wrapping tag or HTML attributes, are listed in the docs.)
P.S. Using the gsub...html_safe method advocated above is very risky. If your app accepts user input for any of the attributes you're printing, calling html_safe on those values means they won't be sanitized by ActionView and a malicious user could inject code into the view that makes your app vulnerable to cross-site scripting (XSS) attacks. Here's a good primer on the ins and outs of html_safe in Rails.
I am having difficulty getting my helper to display a list item. The markup looks like the following:
- #bars.each do |bar|
<% display_bar(bar) %>
The actual helper looks like the following:
module MyHelper
def display_bar(bar)
type = bar.type
concat(%li.type)
concat(%b some text)
concat(%i some more text)
end
end
What am I doing wrong here?
Such things has to be implemented via partials. Or see 5.
<% won't show you anyting. You're in Haml. It's ERb stuff (but even there it wouldn't have shown anything: you'd forgotten the = sign, it should have been <%=).
About concat(%li.type): you cant put your markup inside your Ruby code. Ruby knows nothing about your %li "code".
Amokrane Chentir already mentioned.
You're trying to reinvent the wheel. Rails already provides magnificent helper for such simple cases.
Take a look:
= content_tag_for(:li, #bars) do |bar|
%b= bar.title
%i= bar.id
UPD: content_tag_for sets styles/ids for each li tag based on the current model instance that makes it easy to implement styling/scripting in the future.
The name of your helper is display_bar not display_event.
You should use = instead of <% %>
- #bars.each do |bar|
= display_event(bar)
EDIT
Oops didn't read carefully the content of display_bar method, as #jdoe mentioned you can't use Haml markup syntax in your Ruby code.
My rails 3 app receives emails. Some of them are plain text. When the app displays them to the user I want them to be properly formatted. In other word I want to encode plain text into html. For example: "Hello\n\nHello" => HelloHello (or something like it).
Of course I can write my own 4 lines of code but I am sure those 4 lines have already be written, tested and wrapped in some nice method call.
I know I'm a little late, but I actually think the proper solution to this, at least within Rails, is to leverage the simple_format helper method provided from ActionView::Helpers::TextHelper.
Wrap your text in a Pre tag:
<%= content_tag('pre', "Hello\n\nHello") %>
Using #html_safe, let me explain with an example:
If in your controller the variable is:
#str = "<h1>Hi</h1>"
Then in the view:
<%= #str.html_safe %>
#Batkins has the right answer, which should be accepted.
if someone who is still looking,
Converting plain text to HTML
<%= simple_format("plain text") %>
Converting HTML to proper plain text
text.html_safe
The simple_format is TextHelper module so you if you want to use simple_format method in controller
include ActionView::Helpers::TextHelper
in your controller
render :text => "bla bla bla"
it be useful
http://apidock.com/rails/ActionView/Rendering/render