Non-HTML related Rails snippets
  • In Rails as an HTML container I wrote that, at it's simplest, Rails can be seen as a way to "hydrate" html, and included a small cheat sheet for doing that. There are other parts of building web apps which aren't just about hydrating html. They would've taken up too much space in the original article, so I'm putting them here instead.

  • A simple way to work with external APIs

  • response = HTTParty.get("https://api.github.com/repositories/starred")
  • A simple way to convert data between formats

  • date -> human readable string

  • <%= user.created_at.strftime("%b %e, %H:%M") %>
  • markdown -> html

  • markdown = Redcarpet::Markdown.new(
      Redcarpet::Render::HTML.new(
        hard_wrap: true,
        link_attributes: { target: '_blank' }
      ),
      autolink: true, 
      space_after_headers: true
    )
    markdown.render(content)
  • html -> pdf

  • pdf = WickedPdf.new.pdf_from_string(
        render_to_string('templates/invoice'),
        header: {
            content: render_to_string('templates/invoice')
        }
    )
  • csv -> json

  • records = CSV.parse(File.read("import.csv"), headers: true)
    records.each do |record|
      puts record 
    end
  • A simple way to build json APIs

  • render :json => {
      :success => true,
      :first_name => record.first_name
    }
  • A simple way to send transactional emails

  • UserMailer.welcome_email.deliver_later

  • Website Page