Steven
Steven

Reputation: 13975

Ruby on Rails Edit File Template?

I have a HTML/CSS File laid out with a bunch of areas that need adding. I have a ruby on rails application that would have a bunch of form elements that would then need to be added to this HTML/CSS file (it doesn't need to be shown or anything, just edited and then saved). I don't really understand how I can do this. I was looking at the file class, but got lost very quickly.

Any easy way to do this?

Upvotes: 1

Views: 1741

Answers (1)

Patrick Oscity
Patrick Oscity

Reputation: 54684

Writing to a file in Ruby is very simple:

File.open(filename, 'w') do |f|
  f.write(content)
end

For an example in Rails try the following steps. Generate a new Rails app and a dummy scaffold by running:

rails new erbfun
cd erbfun
rails g scaffold Stylesheet custom_css:text
rake db:migrate
mkdir -p public/system/stylesheets

Then do something like this in your model:

class Stylesheet < ActiveRecord::Base
  require 'erb'

  FOLDER = File.join(Rails.public_path,'system/stylesheets')
  TEMPLATE = <<-CSS
    body {
      font-family: Helvetica;
    }
    <%= custom_css %>
    /* some css comment here ... */
  CSS

  def save_to_file
    template = ERB.new(TEMPLATE)
    document = template.result(binding)
    filename = File.join(FOLDER,"stylesheet-#{Time.now.to_i}.css")
    File.open(filename, 'w') do |f|
      f.write(document)
    end
  end
end

and then try it out:

$ rails c
Loading development environment (Rails 3.2.2)
1.9.3p125 :001 > s = Stylesheet.new custom_css: 'foobar'
 => #<Stylesheet id: nil, custom_css: "foobar", created_at: nil, updated_at: nil> 
1.9.3p125 :002 > s.save!
 ...
 => true 
1.9.3p125 :003 > s.save_to_file
 => 94 
1.9.3p125 :004 > exit

$ cat public/system/stylesheets/stylesheet-1332633386.css
    body {
      font-family: Helvetica;
    }
    foobar
    /* some css comment here ... */

Upvotes: 1

Related Questions