Converting a date to string representation - ruby

I have a date like this:
Date.today - 7
I tried to convert it into a string:
#last_week = strftime((Date.today - 7), '%Y-%m-%d')
But I get the error "undefined method `strftime'". What am I doing wrong?

You can do it like this:
#last_week = (Date.today - 7).strftime('%Y-%m-%d')

This is what you want, but don't do it.:
module Kernel
def strftime(date, format)
date.strftime(format)
end
end
for the reason, see below comments~~~~~

You are trying to use strftime() as though it was a standalone function. In Ruby, there is no such function. The correct way to do this is to call the method Date#strftime().
Here's an example to format today's date as a string:
Date.today.strftime("%m/%d/%y")
Now that you know how to get a date and format the date to a printable string, you can address your specific code need, which is
#last_week = (Date.today - 7).strftime("%Y-%m-%d")
This will give you the date formatted string "2016-04-28" (or thereabouts, depending on when you run the code).

There is no method as strftime on Kernel (although there is such instance method on Date), but you are trying to call such method.
Addition by #Keith Bennett
You are not calling strftime with an explicit object to receive the method, so the Ruby runtime defaults to calling the method on self, which, in this context, is the top level object, an instance of Object, which inherits from BasicObject and includes the Kernel module. None of these contain a strftime method. However, the Date method does have strftime defined. So you can do what you want to do by calling strftime on the calculated Date instance.

Related

Passing Boolean value as a String to a method expecting a String

In Ruby, I'm attempting to pass a boolean result to a method which accepts as a string as a parameter. This is as an experiment.
fileexists = File.file?("#{$fileLocation}")
puts File.file?("#{$fileLocation}")
puts fileexists
puts fileexists.to_s
This will result in:
true
true
true
Now if I attempt to call a method which accepts a string and pass this parameter in a number of ways.
slack(message: "#{fileexists}")
Results in the error message.
'message' value must be a String! Found TrueClass instead.
Which confuses me as I understand that Ruby evaluates anything within "" as a String. So placing a TrueClass object within a placeholder, should effectively cast this value to a string.
So let's try something slightly different:
slack(message: "#{fileexists.to_s}")
This results in the same error.
'message' value must be a String! Found TrueClass instead.
Now this is where things GET REALLY WEIRD!!
slack(message: "#{fileexists.to_s} ")
slack(message: "#{fileexists} ")
If I add a single bit of whitespace to the end of the string after the placeholder, it passes, and a slack message is sent my way, displaying 'true'.
I understand I may be asking for a bit of 'Crystal-ball' insight here as
I don't have the implementation of the 'slack' method, and this may be a result of the way that's implemented.
Does Ruby check types of params as they're passed like this?
Is that a Ruby standard error message you might receive, or a custom error thrown by the slack() method?
The dependency you are using, fastlane, auto-converts values that are passed into the actions (your call to slack).
The reason for this is that parameters in fastlane can also be specified via the commandline, so conversion is necessary. It converts your value of "true" to a boolean automatically because there is no Boolean class in ruby and the type of parameters is specified by giving it the name of a class, so it automatically converts "true" to a boolean. The offending line in the code is here.
As you can see in the code above, a workaround would be to do slack(message: "#{fileexists.to_s.capitalize}") or slack(message: fileexists ? "t" : "f"). Anything really as long as you avoid yes, YES, true, TRUE, no, NO, false, and FALSE
I understand I may be asking for a bit of 'Crystal-ball' insight here as I don't have the implementation of the 'slack' method, and this may be a result of the way that's implemented.
Sounds like youre using a lib (gem) which contains the methods slack, you can check the gem code location running gem which gem_name on your console.
Does Ruby check types of params as they're passed like this?
No
Is that a Ruby standard error message you might receive, or a custom error thrown by the slack() method?
Custom Error
As Jorg W Mittag stated this looks like a misimplementation of slack method when trying to deserialize, and then checking the types. You could fix the slack method on the gem by contributing to this gem, monkeypatch it or you can try to hack it the way it is... this last onde depends on how slack was implemented, maybe adding an extra pair of quotes, like "\"#{fileexists}\""
PS: You don't have to embbed the string inside another string if you're going to use it as it is, like fileexists = File.file? $fileLocation , this should work.
I'm only guessing here because we don't know what the method definition of slack is expecting an un-named String, but you're passing a hash.
slack(fileexists.to_s)

Ruby no method error with HTTParty

I am trying to make a post request in Ruby and I am getting inconsistent behaviour. I am currently using ruby-2.0.0-p598 on OSX.
When using PRY and I type the following post command:
HTTParty.post(#base_uri + '/method/?argument1&api_key=' + #api_key)
I get a successful respond from the API. However when I run it through my specs or inside the class I get:
undefined method `+' for nil:NilClass
I know it has to do with the plus sign, but I find it weird that I am getting a different behaviour. Can you please suggest what is the correct way of doing this?
Thanks in advance.
Good day
Behavior correct - some variable = nil.
You have check variables, or (in this case it is better not to do) call to_s:
HTTParty.post(#base_uri.to_s + '/method/?argument1&api_key=' + #api_key.to_s)
It looks like #base_uri and/or #api_key is null. Please double check if they are initialized with valid strings or not. Then try
HTTParty.post("#{#base_uri}/method/?argument1&api_key=#{#api_key}")
In this case, ruby will automatically try to convert #base_uri and #api_key to string so no need to call to_s method explicitly.

How to pass variable to DB.from in Sequel?

I'm just starting to use Sequel in Ruby, and like it alot.
I want to pass a variable to the "from" method. So instead of calling a method like so:
DB.from(:items)
I'd like to call the method with a variable. For example:
# both of the following approaches fail
tableName = "items"
DB.from(tableName)
DB.from(:tableName)
But it fails with a sql error about a value that's not in my variable. I don't think this is a Sequel issue... I think it's a "I'm new to Ruby" issue.
How can I pass a variable to the from method above?
Do as below using String#to_sym method :
DB.from(tableName.to_sym)
Looking at the documentation of Sequel::Database#from, it seems it accepts all arguments as symbols. Thus you need to convert the string object pointed by the local variable tableName, to a symbol object.

converting Time class object to RFC3339 in Ruby

Google Calendar API(v2)'s time-related query is required to be RFC3339-formatted. When I looked up Time class after 'require "time"', I could not see rfc3339 method.
If you are using ActiveRecord, you can use the to_datetime method to convert the time to a DateTime object.
Time.now.to_datetime.rfc3339 #=> "2014-11-06T10:40:54+11:00"
See:
http://www.ruby-doc.org/stdlib-2.4.1/libdoc/date/rdoc/Time.html.
Does this help? http://www.ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/DateTime.html#method-i-rfc3339
DateTime.parse('2001-02-03T04:05:06.123456789+07:00').rfc3339(9)
#=> "2001-02-03T04:05:06.123456789+07:00"
The way I chose to do this was Time.now.utc.strftime('%FT%TZ')
#=> "2013-08-15T06:13:28Z" which is perfect for an HTML5 type='datetime' input field.
A website mentioned that RFC3339 is most common date format in RSS feeds, so that the conversion method is implemented as #xmlschema, but not #rfc3339.

Ruby DateTime human timezone output

I'm trying to output the timezone of a ruby DateTime object:
DateTime.parse('2012/05/23').strftime('%Z')
This outputs "+00:00". According to the documentation, it should return GMT.
Am I doing something wrong, or have I found a bug?
The DateTime class does not seem to support zone data as zone names. The Time class however does this correctly. So either do this:
require 'date'
require 'time'
Time.parse('...').strftime('%Z')
Or if you already have your data in DateTime format then:
Time.parse(DateTime.parse('...').to_s).strftime('%Z')

Resources