Allows user to edit pages that contain variables [duplicate] - ruby-on-rails

This question already has an answer here:
How to render a string as an erb file?
(1 answer)
Closed 9 years ago.
I have some editable pages that are stored as text in my database. These pages will be called in my view like...
#app/views/static_pages/scheduling_text.html.erb
<%= Page.find_by_name("New Registration").content %>
Page.content is of type 'text' (not string). A portion of the text that contains variables would look like...
You have successfully registered for New Student Orientation on #{<%= #registration.orientation.class_date %>} at...
If course when I call this content in the view, I just get the text, not the model values. How can I make these pages access the model values? I also tried adding #{} around the text without success.

This seems to be a duplicate of Rails: storing erb templates in database
Given that, this should do the trick for you, or at least be close enough to get you started:
<%= sanitize ERB.new(Page.find_by_name("New Registration").content).run %>
Additionally, you can remove the sanitize if content is not user-supplied (this is primarily a security concern).
I've done something exactly like this using HAML processing:
= sanitize Haml::Engine.new(article.content).render
For reference, here's the appropriate ERB documentation: http://ruby-doc.org/stdlib-2.0.0/libdoc/erb/rdoc/ERB.html

OK, after much wailing and gnashing of teeth here is the the solution I cam up with. First I am using mustache. This is much safer than storing erb in the templates and prevents malicious injection of sql into your app. I simply added 'mustache' to my gemfile rather than mustache-rails as it seems to be more up to date. I then created a simple Page model with two attributes: :name and :content. I am using the page model to store the raw mustache code.
Here are the relevant files...
In my controller I call...
#app/controllers/registrations_controller.rb
def create
#registration = Registration.new(params[:registration])
respond_to do |format|
if #registration.save
if #registration.orientation != nil
format.html { render "scheduling_text.html.erb" }
Then my view looks like...
#app/views/registrations/scheduling_text.html.erb
<%= Mustache.render(Page.find_by_name("New Registration").content, {:registration => #registration }).html_safe %>
<%= link_to 'Back', orientations_path %>
...
Then in my page model I have something like...
You have successfully registered for New Student Orientation on {{ registration.orientation.class_date }} at {{ registration.orientation.class_time}}. Please arrive 10 minutes prior to your scheduled Orientation. Remember, you must attend this Orientation session before you may register for classes. ...
Using a page model with scaffolding like this works well because it gives you the new, update, and create actions that will allow users to edit content. Note, they can easily mess up your ruby variables, so thats the downside. Just let your users know to not munk with anything that is between {{}}.
Hope this helps someone else out.

Related

Embedded Ruby not being read when calling html_safe

I'm developing a simple app that teaches people english. The app is based on 5 modules of 34 classes each - 170 total. Each class has its own html page.
Since i dont want to create a view for each class, i scaffolded an Aula model ("class" in portuguese) and saved the html of each class in the model's DB, so i could use only the standard Show view paths to show the classes using their individual id's.
Controller code:
def show
#aula = set_aula
end
These HTML pages are being stored in the database as strings and then being outputted on the Show view using the html_safe method.
#show view code:
<%= #aula.aula.html_safe %>
#"aula" is the DB attribute with the html of each class
It rendered the HTML with no problems, and i got what i wanted. But since i'm creating a rails app, i decided to use embedded Ruby code like <%= link_to %> and <% image_tag %> mixed with the HTML of the classes to create links and show images, and the problem is that these links are being outputted as strings as well, just like any other line, instead of being read and executed as actual Ruby code.
I've been doing a lot of research, but so far I can't find exactly how to make the ERB code be read properly.
Maybe I need to save the HTML in the DB using another data type, or I need to use another method to render the HTML.
First, I'll answer your question, then make a suggestion that you think very carefully before using this approach.
The answer in the post https://stackoverflow.com/a/14351129/483133 shows how to render ERB directly from stored HTML text. Modifying this, here is some code you could use:
def show_html
html = #aula.aula
template = ERB.new(html)
template.result.html_safe
end
# Run this from your controller action, for example, with
def show
#aula = set_aula
end
# inside your view show.erb.html
<%= show_html %>
Warning
I would strongly recommend against finding a solution that allows Ruby code stored in the database to be run. If the pages are able to be written in any way by end users, rather than trusted software developers, then you have opened a huge security hole. Any Ruby code could be run on your server.
I would suggest you consider using a client-side rendering solution (such as Handlebars: http://handlebarsjs.com/ ), which allows for basic rendering of data dynamically in HTML, while not allowing code to be run on your server.

Rails: form generation based on conditions

I've got a form to build a Document. That form needs adjusting depending on what type of Document a user has chosen. At this point I've got a deferring kind of method in new.html.erb that goes like this:
<%= render 'form_'+#template.label.downcase.parameterize.underscore %>
Which works fine but it's kinda difficult to manage though because when new types of documents are added I need to create actual HTML files and upload them.
Is there a better way to manage this kind of form generation? A view with hundreds of if statements in it feels cumbersome too.
You can push it to document_helper or decorator like :
module DocumentHelper
def form_render
return 'form_#{type}'
end
end

How to selectively display fields in new/edit views with custom form builder in rails 3.2.12?

In our rails 3.2.12 app, we would like to selectively display fields in new/edit views (using simple_form) based on the access rules. For example, for sales, only customer's name and phone# can be displayed. Since we don't know what the access rule is going to be, we need to dynamically construct the view at run time. One way to accomplish this is to use if in the views and this would make views messy. We thought customform build might help. After reading a few posts online about custom form builder, we still did not have much clue. Can someone provide details about how to implement this with customform builder? Thanks for help!
UPDATE:
Since we don't know what the access rule is going to be, we need to dynamically construct view at run time.
Usually a custom form builder is used to change the structure of the form's HTML more than to control field access.
A couple of suggestions to "clean up" the views:
Using SimpleForm will let you handle form fields/labels as a unit, making it easier to exclude a field using only something like = form_builder.input :credit_card_number if current_user.admin?.
For a more application-wide solution CanCan can help you manage authorization and roles.
Edit:
Based on your comments, it sounds like the following could be a good approach for you if all the columns are treated the same and you don't need to change their order (using HAML, but you could change it to ERB if necessary):
= simple_form_for #model do |f|
= f.error_notification
- #model.columns_available_for(current_user).each do |column|
= f.input column
You can use rails helpers to do that.
For ex.
module SalesHelper
def show_fields
if current_user.admin?
render 'some_partial' #having name and phone field
else
render 'other_partial'
end
end
end
In your views add respective partials and from new or edit just call
<%= show_fields %>

Dividing text article to smaller parts with paging in Ruby on Rails

This time I've got problem with dividing text article into smaller parts. I don't need to figure out "automatic" algorithm based on words counting or something. All I need is something similar to function which is build-in Wordpress WYSIWYG editor (special breaking page tag).
I thought out only one solution so far. I don't want to divide specific article inside my database. I just want to place some tag inside article and divide it to array in show method.
Sample code:
#controller
#art = Article.find(:id)
if #art.value.contains?('<breaker>')
#parts = art.value.split('<breaker'>)
end
session[:current_part] = params[:current_part] ? params[:current_part] : #parts.first
...
render
#view
<%=h #parts[session[:current_part]] %>
How it sounds for you? It makes any sense? Cant wait for some advices.
It may be better to use an HTML comment so it does not affect the validation of the page.
In your Rails views, in the templates that show text before the breaker, you can split your content like what you have in the example code. I would perform this in a Rails helper module so it can be reused.
To view the full article, your helper method will return the full content if the parameter "more" is passed. The code may look something like this:
# controller
def show
#article = 'Before the break<!--more-->After the break'
end
# app/helpers/application_helper.rb
def show_more(article)
params[:more] ? article : article.split('<!--more-->').first
end
# show.html.erb
<%= show_more(#article) %>
It is generally good practice to keep the application logic in the model and helper files, and keep your controllers as simple as possible.

What's the best way to do UJS in rails when you have a re-usable widget?

In my current project I have a couple instances where I have a re-usable form that exists inside a rails partial. This form submits to a specific controller via ajax (:remote => true). The controller does some stuff and then returns back the appropriate js.erb to modify the page via javascript.
This works fine for when I have a single view. But the problem seems to happen when this re-usable partial exists on multiple views. In view 1 I might want to issue a completely different set of javascript commands then in view 2.
As a concrete example, say I have a comments controller that has the normal CRUD operations.
I now have partial called _comments_box.erb. This _comments_box.erb contains the ability to submit a comment via a simple line:
- form_for comment, :url => post_comments_path(post), :remote => true do |f|
This submits to a comments_controller.rb create method which looks somethings like this:
def create
... do some stuff, like create a new comments model
respond_to do |format|
# will respond with create.js.erb
format.js
end
end
The create.js.erb in turn adds a comment to the view, perhaps doing a bunch of other updates to the DOM.
Say I render the _comments_box.erb within a view called post_summary.erb. Now I have another view, post_detail.erb that requires the same _comments_box.erb. However the post_detail.erb requires me to update completely different divs on the DOM in response to a new comment.
I need to create a different JS response for each instantiation. So I can either:
Create an alternate controller method, say create_2. Pass in some parameter to the _comments_box.erb from post_detail.erb to the _comments_box.erb partial so it knows which controller method to fire. This will allow me to have a separate file _create_2.js.erb that will allow me to manipulate the post_detail.erb view independently.
Forget about using js.erb altogether and just use plain old AJAX and get back JSON, and handle the javascript manipulation completely on the client-side.
It seems option 1 allows me to continue to use the UJS supported by Rails which is nice. But also means I probably will be adding a lot of duplicate code everywhere which is annoying. Is there a way for me to do this elegantly while continuing to use UJS?
That's exactly the purpose of Apotomo: http://apotomo.de/
Here is it's own description:
Apotomo is a true MVC widget framework
for Rails. Widgets are based on Cells
and provide reuseable view components.
Having bubbling events, they know when
and how to update themselves via AJAX!
Working with Apotomo widgets almost
feels like developing GUI components –
in a Rails environment.
Have a try, it's great.
I'd not recommend using UJS for frontend apps: server shouldn't take care of client side business. I agree it's useful and clean but it lacks performance and thus should be kept for backend stuff (RJS will move into a gem, see here: http://weblog.rubyonrails.org/2011/4/21/jquery-new-default).
That said, back to the solutions you expose:
1) I think you won't need an extra controller, you'd just have to pass additional params in order to know from where to query came from. A hidden_field could do the trick. With this info, render the good js.erb file
format.js { if condition
render "create.js.erb"
else
render "create_2.js.erb"
end
}
2) I'd go for it and return json but you'll face the same problem: knowing from where the request comes from.
A better solution (than using a hidden_field) might be to check the request.referer in your controller action. This way you leverage the fact that each context has a unique URL, and don't have to explicitly specify another unique value when rendering your widget partial.

Resources