Parsing a JSON string in Ruby

This looks like JavaScript Object Notation (JSON). You can parse JSON that resides in some variable, e.g. json_string, like so: require ‘json’ JSON.parse(json_string) If you’re using an older Ruby, you may need to install the json gem. There are also other implementations of JSON for Ruby that may fit some use-cases better: YAJL C Bindings … Read more

How to map and remove nil values in Ruby

You could use compact: [1, nil, 3, nil, nil].compact => [1, 3] I’d like to remind people that if you’re getting an array containing nils as the output of a map block, and that block tries to conditionally return values, then you’ve got code smell and need to rethink your logic. For instance, if you’re … Read more

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

Sorry, brief moment of synapse failure. Here’s the real answer. require ‘date’ Time.at(seconds_since_epoch_integer).to_datetime Brief example (this takes into account the current system timezone): $ date +%s 1318996912 $ irb ruby-1.9.2-p180 :001 > require ‘date’ => true ruby-1.9.2-p180 :002 > Time.at(1318996912).to_datetime => #<DateTime: 2011-10-18T23:01:52-05:00 (13261609807/5400,-5/24,2299161)> Further update (for UTC): ruby-1.9.2-p180 :003 > Time.at(1318996912).utc.to_datetime => #<DateTime: 2011-10-19T04:01:52+00:00 … Read more

How to run Rake tasks from within Rake tasks?

If you need the task to behave as a method, how about using an actual method? task :build => [:some_other_tasks] do build end task :build_all do [:debug, :release].each { |t| build t } end def build(type = :debug) # … end If you’d rather stick to rake‘s idioms, here are your possibilities, compiled from past … Read more

Rails 4: List of available datatypes

Here are all the Rails 4 (ActiveRecord migration) datatypes: :binary :boolean :date :datetime :decimal :float :integer :bigint :primary_key :references :string :text :time :timestamp Source: http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_column These are the same as with Rails 3. If you use PostgreSQL, you can also take advantage of these: :hstore :json :jsonb :array :cidr_address :ip_address :mac_address They are stored as … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)