I am making a comic book collection app using Middleman.
I am able to get different information from a YAML file and render it in a .erb file.
Now, I created a date using yaml like this:
date: 1977-08-01
I tried looking around the web on how to render it in different format, but I can't find ANYTHING...
Per example, I have a title field, in my yaml document, that goes like this:
title: "Uncanny X-Men"
So I render it in my erb document using this:
<%= comic["title"] %>
But how do I get, let's say, to print the month from my date? Impossible to find any kind of information... I do get how to use different aspects of dates in either ruby or yaml, but not how to render a date FROM yaml to ruby :(
Thanks!
You need to parse your date value in the YAML file into a Ruby date class, first make sure to surround your date values in the YAML file with quotes like so:
date: '1977-08-01'
and then to parse:
<%= Date.parse(comic["date"]) %>
and to get the month you would add .month
like so:
<%= Date.parse(comic["date"]).month %>
that will give you the number 8 if you want more customization to the way your month look like you should look into strftime, if so you wouldn't even need to use .month.
Ideally to DRY things up, you would create a helper in the config.rb
# Methods defined in the helpers block are available in templates
helpers do
def format_date(date_txt)
date = Date.parse(date_txt)
date.strftime("%B")
end
end
And later you can call it inside your template like so:
<%= format_date(comic["date"]) %>
I hope that helps.
First, check the data type with: comic['date'].class
If it's a Date then you can use: strftime to format the date however you want!
If it's not a date let us know and we'll explain the options for conversion
Related
Below is an erb ruby code which is want to convert in slim template
<div class="star-rating" data-score= <%= review.rating%> ></div>
In above template i am confused as there are two equals to sign
online converter is giving something like this
.star-rating data-score="<haml_loud" review.rating >
But its not working
This will work for you:
.star-rating data-score=review.rating
Since you're (apparently) using Slim, not Haml, you don't need haml_loud at all.
<%= ... > in Erb means to evaluate the expression inside, and include the result in the outer context. Thus if the rating would be 99, then data-score=99 would become part of the html. That is fine.
The generated output seems wrong. The trailing > should be inside a string, just as the opening counterpart "<haml_loud. And as jeffdill2 correctly pointed out, there is no need to use haml_loud. Just use:
.star-rating data-score=review.rating
I'd like to process just links written in markdown. I've looked at redcarpet which I'd be ok with using but I really want to support just links and it doesn't look like you can use it that way. So I think I'm going to write a little method using regex but....
assuming I have something like this:
str="here is my thing [hope](http://www.github.com) and after [hxxx](http://www.some.com)"
tmp=str.scan(/\[.*\]\(.*\)/)
or if there is some way I could just gsub in place [hope](http://www.github.com) -> <a href='http://www.github.com'>hope</a>
How would I get an array of the matched phrases? I was thinking once I get an array, I could just do a replace on the original string. Are there better / easier ways of achieving the same result?
I would actually stick with redcarpet. It includes a StripDown render class that will eliminate any markdown markup (essentially, rendering markdown as plain text). You can subclass it to reactivate the link method:
require 'redcarpet'
require 'redcarpet/render_strip'
module Redcarpet
module Render
class LinksOnly < StripDown
def link(link, title, content)
%{#{content}}
end
end
end
end
str="here is my thing [hope](http://www.github.com) and after [hxxx](http://www.some.com)"
md = Redcarpet::Markdown.new(Redcarpet::Render::LinksOnly)
puts md.render(str)
# => here is my thing hope and ...
This has the added benefits of being able to easily implement a few additional tags (say, if you decide you want paragraph tags to be inserted for line breaks).
You could just do a replace.
Match this:
\[([^[]\n]+)\]\(([^()[]\s"'<>]+)\)
Replace with:
\1
In Ruby it should be something like:
str.gsub(/\[([^[]\n]+)\]\(([^()[]\s"'<>]+)\)/, '\1')
I have a var in my view returning date and time from a datetime database record as UTC format. The output looks like this: 2014-01-21 03:13:59 UTC
How do I format this? Date.parse(var) will give #=> Tue, 21 Jan 2014 in IRB but a type error in RAILS 4 of: "no implicit conversion of ActiveSupport::TimeWithZone into String"
I ultimately would like to display just the date; formatted as: %m/%d/%Y My only option can't be to: to_s and regex this right? Someone please show me the RAILS way.
Use Date#strftime:
Date.parse('2014-01-21 03:13:59 UTC').strftime('%m/%d/%Y')
# => "01/21/2014"
If var is TimeWithZone object, just call TimeWithZone#strftime method:
var.strftime('%m/%d/%Y')
I would argue that Rails' way is to name that format in an initializer and to use the named date format with the to_formatted_s (or its to_s alias):
# in config/initializers/date_time_formats.rb
Time::DATE_FORMATS.merge!(date_us: '%m/%d/%Y')
Date::DATE_FORMATS.merge!(date_us: '%m/%d/%Y')
And then use this named format in your view like this:
<%= #object.date.to_s(format: :date_us) %>
This allows you to reuse this named format in your application without writing the complex strftime string multiple times. You can add several different formats and have one place in your app to change all existing formats.
If you are going to localize your application into different languages then you might want to consider storing those formats in your locale YAML files. This allows you to use different formats depending on the user's location. Read more about it in the official Rails Guide about I18n.
I just started checking out sinatra for a project, and I started playing around with HAML.
However, I've run in to an issue -- I have a path with a splat that needs to point to an HAML file with a name the same as the text splatted out of the url, however, any string passed to the [haml] template method is treated as an inline template, and not a filename.
There is no documentation that would suggest there is a way to do this. The only solution I can think of is reading to full text of the necessary template file and passing it to the HAML function; however, such a solution is incredibly cumbersome.
Example
get '/stpl/*.haml' do |page|
haml page # <--- `page' is treated as an inline template
end
Whilst this functionality is expected when one reads the documentation, there is no other means, it would seem, to accomplish what I need.
If you pass a symbol to haml, it will look in views for the matching file, so you can do this instead:
get '/stpl/*.haml' do |page|
haml page.to_sym # attempts to get views/<page>.haml
end
I am having an array like "author","post title","date","time","post category", etc etc
I scrape the details from a forum and I want to
save the data using ruby
update the data using ruby
update the data using text editor or I was thinking of one of OpenOffice programs? Calc would be the best.
I guess to have some kind of SQL database would be a solution but I need quick solution for that (somthing that I can do by myself :-)
any suggestions?
Thank you
YAML is your friend here.
require "yaml"
yaml= ["author","post title","date","time","post category"].to_yaml
File.open("filename", "w") do |f|
f.write(yaml)
end
this will give you
---
- author
- post title
- date
- time
- post category
vice versa you get
require "yaml"
YAML.load(File.read("filename")) # => ["author","post title","date","time","post category"]
Yaml is easily human readable, so you can edit it with any text editor (not word proccessor like ooffice). You can not only searialize array's and strings. Yaml works out of the box for most ruby objects, even for objects of user defined classes. This is a good itrodution into the yaml syntax: http://yaml.kwiki.org/?YamlInFiveMinutes.
If you want to use a spreadsheet, csv is the way to go. You can use the stdlib csv api like:
require 'csv'
my2DArray = [[1,2],["foo","bar"]]
File.open('data.csv', 'w') do |outfile|
CSV::Writer.generate(outfile) do |csv|
my2DArray.each do |row|
csv << row
end
end
end
You can then open the resulting file in calc or in most statistics applications.
The same API can be used to re-import the result in ruby if you need.
You could serialize it to json and save it to a file. This would allow you to edit it using a simple text editor.
if you want to edit it in something like calc, you could consider generating a CSV (comma separated values) file and import it.
If I understand correctly, you have a two-dimensional array. You could output it in csv format like so:
array.each do |row|
puts row.join(",")
end
Then you import it with Calc to edit it or just use a text editor.
If your data might contain commas, you should have a look at the csv module instead:
http://ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html