Using a template to generate json to send to web service - ruby-on-rails

I am generating some json to send to a web service.
Currently I am creating a hash, loading it with the data and then calling to_json to generate the json string to send.
But I figure it would be much cleaner and more rails like if I could use a template in a .erb file to generate the json for me.
All the info I can find on erb files use it to create data to send back to the client. I dont want to do this, I am the client here!
How can I do this?

ERB template engine is something you can use without Rails, actually.
require 'erb'
x = 42
template = ERB.new <<-EOF
The value of x is: <%= x %>
EOF
puts template.result(binding)
In your case you can use a template like
{ foo: <%= model.foo.inspect %>, bar: <%= model.bar.inspect %> }
Store it in a .erb file, read the contents with File.open and then pass it to ERB.new, like in the example.
More info here: http://ruby-doc.org/stdlib/libdoc/erb/rdoc/classes/ERB.html

Related

Opening .html.erb files in browser

Is there a way to open .html.erb files by themselves in the browser. The Rails app I am trying to have a look at is in rails 2.3 and will not run locally on the rails server nor will it run when I give the command script/server.
I would just like to open the individual views in the browser by themselves...is this possible?
You can open them in the browser, but the <% %> and <%= %> tags will get shown as-is instead of executing the Ruby code. These are template files that need to get processed by Rails to fill in data at runtime. Your best bet is TsaiKoga's answer, making a controller action render the template in question.
In rails4 you can do it like this:
erb a.html.erb > a.html
Maybe it doesn't work in rails 2.3. If you want to render that view, maybe you can use an action just like users#index and change the code to render it:
render "devise/mailer/a.html.erb", :layout => false

Create a Text File From a Form Server Side Ruby on Rails

I am using Ruby on Rails and have a form that gets information from user input. I then want to take the user input and write it to a text file on the server side. I hope to save the file in somewhere such as /public/UserInput.txt.
Is there a way to use Ruby on Rails to do this? Or do I need a different language to do this such as PHP? In either case can anyone give me an example of how this is to be done?
Thanks in advance.
Update
The code I am trying that is not giving me a text file is:
after_save :create_file
def create_file
parameter_file = File.new('C:\\parameter_file.txt', "w")
parameter_file.puts(:parameter)
end
This isn't really a rails specific problem. It can be tackled in plain ruby.
path = "/some/file/path.txt"
content = "data from the form"
File.open(path, "w+") do |f|
f.write(content)
end
where target is where you want the file to go, and content is whatever data you're extracting from the form.

Rails automatically escpaping HTML - how to stop it?

I'm working on upgrading an old Rails app (1.1.6) to Rails 3. Obviously, a lot has changed. One thing appears to be that Rails automatically escapes content dropped into the view. However, I have a situation where I have a helper generating IMG tags for me, and Rails is automatically escaping the resulting content.
<%= random_image('public/images/headers') %>
This results in escaped content, much like one would expect had I done this (in 1.1.6)
<%= h random_image('public/images/headers') %>
Is there a way to tell it to not escape?
<%= raw random_image('public/images/headers') %>
.html_safe
It may need to be inside the helper
There are there ways in which this can be achieved in rails 3 application
html_safe
raw
h
raw and h can only be used in controller and views these methods are defined in helpers.
html_safe can be used anywhere in a rails application i.e., can be used in models, helpers, controller etc.
For more information please read http://yehudakatz.com/2010/02/01/safebuffers-and-rails-3-0/

Is there any gem can dump the data from and to yml files?

I'm find such a gem a whole day, but not find a good one. I want to write one, but I'm not able to do it.
The data in my database may be English text, which will be dump to a yml file with plain text. And some are non-English text, which will be binary type.
And both of them may have such code:
<% xxx %>
When I use rake db:fixtures:load to load them into database, error may occur: method xxx not found.
I wan't to find a good gem can handle this problem. Thank for any help
UPDATE
I have gave up finding such a gem. At first, I think it's a easy task, but now, after some researchings, I have to say, it's much harder than I expected.
The reason you are having problems is because the Fixture loader will pass your fixture through erb before loading the data. This means that if you have <% xxx %> in your yaml file then Rails will see that as erb and try to run a method called xxx.
There does not seem to be an easy way to turn off erb processing of fixtures. I have tried replacing the fixtures with CSV fixtures and this still does ERB pre-processing.
Without a simple answer I have to ask the question Why do you have these strings in your file?
Do you want them to be expanded by erb?
Err...I'm not sure if you actually need a gem for this? Rails natively can turn any model into YAML.
Let's say you have a model called "Objects". You could hit a route that looks like:
/objects.yaml
and you would get a giant text file of all your Objects in YAML form.
Of course, you would want to have something like:
respond_to do |format|
format.yaml {render :yaml => #objects}
end
in your restful controller.
If you'd rather not hit a route to do this, you can always do
#yaml = []
#objects.each do |object|
#yaml.push object.to_yaml
end
anywhere in ruby, which will give you an array of yaml objects, that you can then write to a file at your leisure.
I imagine that if rails itself is generating the yaml, then it would be able to then later load it as a fixture?

Rails -- How to save HTML output of a HAML partial as a string to send to an external service?

We are generating a newsletter automatically every 24 hours using a rake task. There's a section at the top of the newsletter where an admin can put a customized message. The screen that the admin uses has a live preview of the newsletter (they were insistent on this), rendered using a haml partial that takes a collection.
In order to generate and send the emails, we are sending xml documents to a third party API that contain (among other things) the HTML for the email that we'd like to generate.
What I want to do is save the output of this haml partial within a rake task, something similar to PHP's ob_*() buffering functions. Is there any way to do something like the following:
ob_start();
render :partial => newsletter, :collection => posts
newsletter_html = ob_get_contents()
xml = "
<Creative>
<Name>Our Newsletter -- #{Time.now.strftime('%m/%d/%Y')}</Name>
<HTML><html><body>#{newsletter_html}</body></html></HTML>
...
</Creative>"
I'm probably missing something obvious, and I could think of a few ways to do this but most of them are not DRY and I don't want to be generating a lot of html in the helpers, models, or the task itself.
Let me know if there is a way for me to accomplish this.
A more direct approach from the HAML docs:
require 'haml'
haml_string = "%p Haml-tastic!"
engine = Haml::Engine.new(haml_string)
engine.render #=> "<p>Haml-tastic!</p>\n"
You'll have to do a bit of work loading up the HAML template and setting up any local variables that need interpolation, but the flexibility may make up for that.
A common way to do this (which is typically advised against) is to render into a string in your model or rake task:
cached_content =
ActionView::Base.new(Rails::Configuration.new.view_path).render(:partial => "newsletter", :locals => {:page => self,:collection => posts})
see here for a more full description:
http://www.compulsivoco.com/2008/10/rendering-rails-partials-in-a-model-or-background-task/
If you are using page or fragment caching, you could pull the content out of the cache. The easiest way to do this is to just enable caching, and then look at where the files are being placed.
http://guides.rubyonrails.org/caching_with_rails.html
A bit of a shot in the dark but if you check out the rdoc for Haml it more than likely has a method which accepts a string and some variables and then renders the output.
With ERB it would look something like:
require 'erb'
name = 'world'
template = 'hello <%= name %>'
template = ERB.new(template)
puts template.result(binding)

Resources