Rails ActiveSupport: How to assert that an error is raised?

So unit testing isn’t really in activesupport. Ruby comes with a typical xunit framework in the standard libs (Test::Unit in ruby 1.8.x, MiniTest in ruby 1.9), and the stuff in activesupport just adds some stuff to it. If you are using Test::Unit/MiniTest assert_raise(Exception) { whatever.merge } if you are using rspec (unfortunately poorly documented, but … Read more

How to encode media in base64 given URL in Ruby

To encode a file: require ‘base64’ Base64.encode64(File.open(“file_path”, “rb”).read) To produce the file from the encoded string: require ‘base64’ encoded_string = Base64.encode64(File.open(“file_path”, “rb”).read) File.open(file_name_to_create, “wb”) do |file| file.write(Base64.decode64(encoded_string)) end

Convert UTC to local time in Rails 3

Time#localtime will give you the time in the current time zone of the machine running the code: > moment = Time.now.utc => 2011-03-14 15:15:58 UTC > moment.localtime => 2011-03-14 08:15:58 -0700 Update: If you want to conver to specific time zones rather than your own timezone, you’re on the right track. However, instead of worrying … Read more

How to use Active Support core extensions

Since using Rails should handle this automatically I’m going to assume you’re trying to add Active Support to a non-Rails script. Read “How to Load Core Extensions”. Active Support’s methods got broken into smaller groups in Rails 3, so we don’t end up loading a lot of unneeded stuff with a simple require ‘activesupport’. Now … Read more

What is mattr_accessor in a Rails module?

Rails extends Ruby with both mattr_accessor (Module accessor) and cattr_accessor (as well as _reader/_writer versions). As Ruby’s attr_accessor generates getter/setter methods for instances, cattr/mattr_accessor provide getter/setter methods at the class or module level. Thus: module Config mattr_accessor :hostname mattr_accessor :admin_email end is short for: module Config def self.hostname @hostname end def self.hostname=(hostname) @hostname = hostname … Read more

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