Datamapper DateTime to String behaviour - ruby

I write my first project wich using Datamapper as ORM, so please be patient. :)
I try to do get String from DateTime field:
Error.first.submitted_at.to_s
=> "2009-08-24T12:13:32+02:00"
Returned String is not good for me. In ActiveRecord I can do something like that:
Error.first.submitted_at.to_s(:only_date)
or any other date formatter. Is somethig similar available in DataMapper or I must to use strftime method?

That's a feature available using AcitveSupport. You can do require 'activesupport' to get it. That might be overkill, though. You could also use #stamp from Facets to do the same thing, but you have to set up the :only_date format:
require 'facets/date'
Date::FORMAT[:only_date] = '%d.%m.%y' # For Date objects
Time::FORMAT[:only_date] = '%d.%m.%y' # For DateTime objects
d = DateTime.now
d.stamp(:only_date) # => "24.08.09"
If you really want to use it with the to_s method, you can do that, too:
require 'facets/date'
Date::FORMAT[:only_date] = '%d.%m.%y' # For Date objects
Time::FORMAT[:only_date] = '%d.%m.%y' # For DateTime objects
class DateTime
alias :default_to_s :to_s
def to_s(format=nil)
if format.nil?
default_to_s
else
stamp format
end
end
end
d = DateTime.now
d.to_s(:only_date) # => "24.08.09"

Related

How to set date interpretation/format?

I am dynamically updating the underlying model by passing the parameters from the posted form to the model like this:
#model.assign_attributes(params[:model])
I have a date coming in along with the rest of the post data in the format mm/dd/yyyy. Ruby appears to be parsing this date as if it is in the format dd/mm/yyyy, as far as I can tell. So, when I enter a date of 4/15/2014, for instance, the model fails to save because the month 15 does not exist (I assume, in reality I am just told that the date field is required).
How can I configure Ruby to parse my dates as mm/dd/yyyy?
Use the strptime method for date and supply the format.
Date.strptime("4/15/2014","%m/%d/%Y")
#=> #<Date: 2014-04-15 ((2456763j,0s,0n),+0s,2299161j)>
You will probably have to specify a call back like before_update if you want the conversion to happen in the model.
e.g.
class YourModel < ActiveRecord::Base
before_update :format_date
def format_date
date_field = Date.strptime(date_field,'%m/%d/%Y')
end
end

How do I retrieve timezone code from a Ruby Timezone object?

I'm using Ruby 1.9.3 with gems timezone 0.3.1 and tzinfo 0.3.38.
I'm looking to retrieve the current timezone code for a timezone, e.g. 'EST' for 'America/New_York' right now, or 'EDT' in the summer.
I've found nothing in the documentation, yet when I dump the object with the following code:
ptz = Timezone::Zone.new :zone => 'America/New_York'
hash = {}
ptz.instance_variables.each do |var|
hash[var.to_s.tr('#','')] = ptz.instance_variable_get var
end
puts hash.to_json
there is an array of 267 "rules", each a hash where "name" contains the value I am looking.
Does anyone know how I should determine which rule is current, so I can retrieve the name value?
require 'tzinfo'
tz = TZInfo::Timezone.get('America/New_York')
tz.strftime("%Z")
=> "EST"
TZInfo::Timezone.get('America/New_York').period_for_utc(Time.now).abbreviation gives you the abbr. for the time provided.

Mapping XML to Ruby objects

I want to communicate between ruby and other applications in XML. I have defined a schema for this communication and I'm looking for the best way to do the transformation from data in Ruby to the XML and vice versa.
I have an XML document my_document.xml:
<myDocument>
<number>1</number>
<distance units="km">20</distance>
</myDocument>
Which conforms to an Schema my_document_type.xsd (I shalln't bother writing it out here).
Now I'd like to have the following class automatically generated from the XSD - is this reasonable or feasible?
# Represents a document created in the form of my_document_type.xsd
class MyDocument
attr_accessor :number, :distance, :distance_units
# Allows me to create this object from data in Ruby
def initialize(data)
#number = data['number']
#distance = data['distance']
#distance_units = data['distance_units']
end
# Takes an XML document of the correct form my_document.xml and populates internal systems
def self.from_xml(xml)
# Reads the XML and populates:
doc = ALibrary.load(xml)
#number = doc.xpath('/number').text()
#distance = doc.xpath('/distance').text()
#distance_units = doc.xpath('/distance').attr('units') # Or whatever
end
def to_xml
# Jiggery pokery
end
end
So that now I can do:
require 'awesomelibrary'
awesome_class = AwesomeLibrary.load_from_xsd('my_document_type.xsd')
doc = awesome_class.from_xml('my_document.xml')
p doc.distance # => 20
p doc.distance_units # => 'km'
And I can also do
doc = awesome_class.new('number' => 10, 'distance_units' => 'inches', 'distance' => '5')
p doc.to_xml
And get:
<myDocument>
<number>10</number>
<distance units="inches">5</distance>
</myDocument>
This sounds like fairly intense functionality to me, so I'm not expecting a full answer, but any tips as to libraries which already do this (I've tried using RXSD, but I can't figure out how to get it to do this) or any feasibility thoughts and so on.
Thanks in advance!
Have you tried Nokogiri? The Slop decorator implements method_missing into the document in such a way that it essentially duplicates the functionality you're looking for.

Rails 3.2 - validate format of date

I have the model Teacher which has field :teacher_birthday. I get :teacher_birthday from the view (a single textbox). I want to make sure that an input date has a such format - dd.mm.yyyy (i mean i want to be sure, that an input date as 12.24.1991 will not be save in db because such date is wrong) and that this date exists. Also, i want to do this in the MODEL. Is this possible?
Try the chronic gem. It has very flexible date parsing, including what you're looking for:
[11] pry(main)> require 'chronic'
=> true
[12] pry(main)> Chronic.parse('24.12.1991'.gsub('.','-'))
=> 1991-12-24 12:00:00 -0700
Declare the validation method to be called in your model, and then define this method. The following should roughly do what you need:
validate :validate_teacher_birthday
private
def validate_teacher_birthday
errors.add("Teacher birthday", "is invalid.") unless (check_valid_date && valid_date_format)
end
def valid_date_format
self.teacher_birthday.match(/[0-9][0-9].[0-9][0-9].[0-9][0-9][0-9][0-9]/)
end
def check_valid_date
begin
parts = self.teacher_birthday.split(".") #contains array of the form [day,month,year]
Date.civil(parts[2].to_i,parts[1].to_i,parts[0].to_i)
rescue ArgumentError
#ArgumentError is thrown by the Date.civil method if the date is invalid
false
end
end

Exploding date string into separate span elements in Ruby

I'm looking for the best way to take a datetime string from MySQL, explode it in Ruby and return the month, date, and year in separate elements.
How is the string formatted? You could just convert the datetime string into a datetime object, and call the instance methods.
require 'time'
x = "2009/04/16 19:52:30" #grab your datetime string from the database and assign it
y = DateTime.strptime(x, "%Y/%m/%d %H:%M:%S") #create a new date object
Then a simple y.day() yields:
y.day() = 16
and y.hour():
y.hour() = 19
FYI never actually used Ruby much, so this is what I got out of playing with the console, so hopefully this helps shed some light.
require 'time'
x = "2009/04/16 19:52:30"
begin
y = Time.parse(x)
[y.year, y.month, y.day] # => [2009, 4, 16]
rescue ArgumentError
puts "cannot parse date: #{x}"
end

Resources