For instance, if I called:
gmdate("M-D-yTh:i:s")
Is there something similar for this case in RoR? I guess I could always DateTime.now.hour, DateTime.now.year, etc. etc. but that seems extremely wrong.
See strftime() in Ruby's documentation on Time, which formats a time according to the directives in the given format string.
Related
Simple question, in terms of best practice is it better to format my URL like this:
http://www.example.com/search?query=hello&page=1
or like this:
http://www.example.com/search/hello/page/1
Can you provide a valid reason for your choice please.
First one fits the situation where you want to "filter" your result if it gets a little too complicated, like this example:
cars.com/audi/sedan/a/4/black/manual.....
this is gonna take so long and complicated and result will be nightmare, but this would work better:
cars.com/mercedes/amg?color=white&transmission=manual
2nd way is just like thinking it of a 'folder'ed structure:
socialmedia.com/shares/1/comments/1/page/2
I am pretty sure you get the idea.
p.s. if you will provide your API to a brand new clients, who don't know anything about it, then first one is also more understandable but, i suggest you also have a API documentation which describes the parameters and the relevant poasible other calls as well. in this way your url formatting will be clearer and clients will not struggle to solve parameters in the url.
The first way is not only functional, but lets a human understand what the name/value pairs are. Sure you could go into configuration and string manipulation and make your URL look like the second example and still function, but from a readability pov and ease of function, the first one is best.
I have a question.
I have comment model, in which it has body column that users can type anything in there.
obviously user might type the url link to other website.
In my guess, I think it should be replaced with < a href > tag when it is being saved.
Is there any good gem or something to handle this kind of thing?
If you don't want to use a full-blown markdown parser (Redcarpet), use Rinku. It's super fast and safe. Do not use any regex based solutions as you would most likely open yourself to security risks.
text = "Hello! Check this out: https://github.com/vmg/rinku"
Rinku.auto_link(text, mode=:all, link_attr=nil, skip_tags=nil)
Produces:
=> "Hello! Check this out: https://github.com/vmg/rinku"
Preserving for posterity's sake, but I feel it's important to note that this is NOT a secure way to solve the problem. Unless you want to figure out all the security implications for yourself, don't follow this advice. Jiří Pospíšil's answer is better. =D
You don't really need a gem to do that (I personally try to avoid gems for something so simple). Write a regular expression that is reasonably reliable for your purposes, and then use something like
input.gsub(regex, 'some text')
to convert the links into their html equivalent. Note that you'll need to use raw to display the results of this, otherwise rails will escape the output for you. This also means users will be able to put other arbitrary markup in, unless you escape it as it goes into the database. Make sure you do that.
Alternately, you could do the same thing as you display it, with slightly different considerations/steps necessary.
I need to produce a date in Rails which looks like this:
/Date(1294268400000)/
I have tried various combinations of DateTime, to_i, to_json but never managed to get the /Date()/ thing.
Do I have to simply get my date in ms and then wrap the /Date(and )/ manually, or is there a built in method?
What about (ruby 1.9.x)?:
Time.now.strftime("/Date(%s%L)/")
=> "/Date(1335280866211)/"
You should try
new Date(posixMillisecondsHere)
first. MDN says that calling the Date function outside of the constructor context (i.e., without the new) will always return a string containing a formatted date rather than a Date object.
Strictly speaking, when you do that, you are writing JavaScript and not JSON. JSON cannot contain Date objects.
RFC 4627 says
2.1. Values
A JSON value MUST be an object, array, number, or string, or one of
the following three literal names:
false null true
If you want to put a Date into what is strictly considered JSON and then get it back out, you must choose some way of using the JSON primitives (to wit, objects, arrays, numbers, strings, etc.) to encode a Date.
If you want to get a Date back out of JSON, whatever parses your JSON must understand the convention that you used to encode the Date.
Hope these are credible and/or official enough to help.
What about something like this:
in your config/en.yml file:
en:
time:
formats:
json: "/Date(%s%L)/"
and than in the view:
<%= l(Time.now, :format => :json) %>
Please note that you would need access to the helpers in the method that renders json. So it won't work if you are using ActiveRecord#to_json method for generating jsons.
Check out this question:
c# serialized JSON date to ruby
... simple answer seems to be to create a parse_date method.
It's the UNIX Epoch (seconds since 1970-01-01) right? What about using DateTime#strftime method?
# Taken from the Ruby documentation
seconds_since_1970 = your_date.strftime("%s")
UPDATE: OK, it's milliseconds, according to the documentation you can use your_date.strftime("%Q") to get the ms (but I've not tried yet).
Using ActiveRecord::Base.to_json I do:
user = User.find_by_name 'Mika'
{"created_at":"2011-07-10T11:30:49+03:00","id":5,"is_deleted":null,"name":"Mika"}
Now, what I would like to have is:
{
"created_at":"2011-07-10T11:30:49+03:00",
"id":5,
"is_deleted":null,
"name":"Mika"
}
Is there an option to do this?
It would be great to have a global option, so that the behaviour be set depending on dev/live environment.
I'll go out on a limb and say "no, there is no such option".
AFAIK, the JSON encoding is actually handled by ActiveSupport rather than ActiveRecord. If you look at lib/active_support/json/encoding.rb for your ActiveSupport gem, you'll see a lot of monkey patching going on to add as_json and encode_json methods to some core classes; the as_json methods are just used to flatten things like Time, Regexp, etc. to simpler types such as String. The interesting monkey patches are the encode_json ones, those methods are doing the real work of producing JSON and there's nothing in them for controlling the final output format; the Hash version, for example, is just this:
# comments removed for clarity
def encode_json(encoder)
"{#{map { |k,v| "#{encoder.encode(k.to_s)}:#{encoder.encode(v, false)}" } * ','}}"
end
The encoder just handles things like Unicode and quote escaping. As you can see, the encode_json is just mashing it all together in one compact string with no options for enabling prettiness.
All the complex classes appear to boil down to Hash or Array during JSONification so you could, in theory, add your own monkey patches to Hash and Array to make them produce something pretty. However, you might have some trouble keeping track of how deep in the structure you are so producing this:
{
"created_at":"2011-07-10T11:30:49+03:00",
"id":5,
"is_deleted":null,
"name":"Mika"
"nested":{
"not":"so pretty now",
"is":"it"
}
}
Would be pretty straight forward but this:
{
"created_at":"2011-07-10T11:30:49+03:00",
"id":5,
"is_deleted":null,
"name":"Mika"
"nested": {
"not":"so pretty now",
"is":"it"
}
}
would be harder and, presumably, you'd want the latter and especially so with deeply nested JSON where eyeballing the structure is difficult. You might be able to hang a bit of state on the encoder that gets passed around but that would be getting a little ugly and brittle.
A more feasible option would be an output filter to parse and reformat the JSON before sending it off to the browser. You'd have to borrow or build the pretty printer but that shouldn't be that difficult. You should be able to conditionally attach said filter only for your development environment without too much ugliness as well.
If you're just looking to debug your JSON based interactions then maybe the JSONovich extension for Firefox would be less hassle. JSONovich has a few nice features (such as expanding and collapsing nested structures) that go beyond simple pretty printing too.
BTW, I reviewed Rails 3.0 and 3.1 for this, you can check Rails 2 if you're interested.
Have you considered the JSON gem? I believe it does exactly what you're looking for.
e.g.
JSON.pretty_generate(user)
Have a look at the detail here...
http://apidock.com/ruby/JSON/pretty_generate
does anyone knows a file format for configuration files easy to read by humans? I want to have something like tag = value where value may be:
String
Number(int or float)
Boolean(true/false)
Array(of String values, Number values, Boolean values)
Another structure(it will be more clear what I mean in the fallowing example)
Now I use something like this:
IntTag=1
FloatTag=1.1
StringTag="a string"
BoolTag=true
ArrayTag1=[1 2 3]
ArrayTag2=[1.1 2.1 3.1]
ArrayTag3=["str1" "str2" "str3"]
StructTag=
{
NestedTag1=1
NestedTag2="str1"
}
and so on.
Parsing is easy but for large files I find it hard to read/edit in text editors. I don't like xml for the same reason, it's hard to read. INI does not support nesting and I want to be able to nest tags. I also don't want a complicated format because I will use limited kind of values as I mentioned above.
Thanks for any help.
What about YAML ? It's easy to parse, nicely structured has wide programming language support. If you don't need the full feature set, you could also use JSON.
Try YAML - is (subjectively) easy to read, allows nesting, and is relatively simple to parse.