Back in January I announced a small but useful plugin called AppConstants, that basically provides a central place where you can store environment specific constants. And since I started using Rails 3 in the past week, I thought I’d make it Rails 3 compatible.
The code is really simple and - as I expected - the upgrade process was quite straight forward.
I’m not gonna write a guide here on how to upgrade your plugins to Rails 3 - there is plenty about that around the web - but instead, just show the steps I went through to upgrade mine. Similar plugins might have a similar upgrade path.
- Generators
My plugin makes use of a simple generator that copies its default constants file and initializer to Rails.root/config and Rails.root/config/initializers, respectively. In Rails 2.x it was located under Rails.root/vendor/plugins/app_constants/generators/app_constants and it was defined like so:
class AppConstantsGenerator <Rails::Generator::Basedef manifest
record do|m|
m.directory('config')
m.file('constants.yml', 'config/constants.yml')
m.directory('config/initializers')
m.file('load_app_constants.rb', 'config/initializers/load_app_constants.rb')endendend
In Rails 3, the generators had to be moved to Rails.root/vendor/plugins/app_constants/lib/generators. Notice the root directory app_constants under generators has been removed as well. And the code was changed to this:
class AppConstantsGenerator <Rails::Generators::Basedefself.source_root@source_root||= File.expand_path('../templates', __FILE__)enddef copy_config_files
copy_file('constants.yml', 'config/constants.yml')
copy_file('load_app_constants.rb', 'config/initializers/load_app_constants.rb')endend
We had three simple changes here:
- The generator now extends from Rails::Generators::Base: This class uses the Thor infrastructure to handle generators. - more info here.
- I had to implement the source_root class method, which basically tells your generator where to find your template files.
- The manifest method is now called copy_config_files - or anything you want.
The way this works is that, once you invoke the generator, Thor will sequentially call all instance methods in your generator class - or the only instance method in the example above. If your generator does a lot, it will allow for a better organization of your tasks.
And that’s it! I did change a couple of other things but that had to be changed anyway and are not related to the migration.
For Rails 2.3.x users, you’ll find a 2.3.x branch on github that should work for you.
Learning new programming languages is fun. And if it’s your 2nd, 3rd…Nth programming language you will eventually look for features you already know and love.
Coming from Ruby - but after having done my fair amount of Java for many years, among other things - I end up looking for features like blocks, open classes and syntax sugar like automatic generation of attribute accessors. These are hard to let go of.
Having decided to learn Objective-C recently, I was delighted to find out that all of these are available - for better or for worse - and wanted to share this analogy with its Ruby counterparts.
- Attribute accessors
In ruby, this class definition
class Person
attr_accessor :nameend
implements for you the getters and setters of the instance variable name.
In Objective-C, the combination of the @property and @synthesize directives provides you with roughly the same result:
// in the interface file@interface Person :NSObject{NSString*name;
}
@property(retain)NSString*name;
@end//in the implementation file@implementation Person
@synthesize name;
@end
Now the compiler is responsible for writing those getters/setters for you.
- Open classes & blocks
Blocks in ruby are the structures that allow you to - among other things - iterate over arrays like this:
my_array.eachdo|item|puts(item)end
Objective-C doesn’t have an ‘each’ method in its root array class (NSArray) but since it does support blocks and open classes, you could just write it yourself:
//in the interface file@interfaceNSArray(each)-(void) each:(void(^)(id*))block;
@end//in the implementation file@implementationNSArray(each)-(void) each:(void(^)(id*))block {for(id*object in self){
block(object);
}}@end
Yes, I know the syntax isn’t appealing, but using it in your program is a bit better:
Given the syntactic differences, the code above is very similar to its ruby counterpart. Iterating over an array is just one of the many things blocks are useful for. Others might include dealing with files, network sockets etc…
Blocks are powerful structures and are not created everyday, but it’s nice to know that you can resort to them when the time comes.
In Ruby you have basically two ways of defining private methods:
# this is the first way to do itclassTestdef say_hello
puts"I'm a private method"end
private :say_helloend# and this is the second wayclassTest#other methods this class might have
private
def say_hello
puts"I'm a private method"endend
I see a small problem with both approaches. In the first one, and the most obvious, is that you need to duplicate the method name as well as add an extra method call - private - just to change its visibility.
The second approach avoids this but adds the risk of accidentally putting a method that is intended to be public under the private section of the source file, which can render an annoying debugging session.
Why?
Personally, I like to have a smooth reading flow in my source files. That means that if the public method_a makes use of the private method_b, I want method_b defined right below its caller, which is possible - but verbose - using the private method call:
But can be somewhat harder to accomplish if you decide to split your source file in sections:
classTestdef method_a
method_b
end#just another public method. We might have severaldef method_c
method_b
end
private
def method_b
puts"I'm a private method"endend
I wanted to be able to define a private method with a single reserved keyword…
How?
What if I could define a private method using this new syntax:
classTest
def_p say_hello
puts"I'm a private method"endend
It turns out I can.
Notice the def_p keyword? This is a new keyword I created by changing ruby’s parser and that behaves mostly like the def keyword, except that it defines a private method instead.
If you wanna read the code that allows this behavior and try it yourself, download the patch I wrote and apply it to the ruby source code - I patched version 1.9.1-p376.
After applying the patch, just build ruby as usual:
$ ./configure
$ make
And then try running this script:
classTest
def_p say_hello
puts"I'm a private method"endendTest.new.say_hello
You should see the following output:
pvt.rb:10:in`': private method `say_hello' called for# (NoMethodError)
Today I read a nice post - in Portuguese - by Fábio Akita on how to manage multiple ruby versions on your machine. I’ve tried it once with some tool I can’t even remember the name but failed miserably.
But this time things look very different. The tool here is the rvm - short for Ruby Version manager - and it works just great.
Let’s cut to the chase and imagine that you, like me, want to run/develop/test your code on both ruby 1.8.7 and ruby 1.9.1. These steps would get you up and running in a few minutes:
Now it’s important to notice that at this point you have separate gem installations for each of the interpreters you’ve installed in the previous step. That said, just go ahead and switch between your interpreters and use your command line scripts - ruby, gem, etc… - as usual.
Switching between interpreters:
$ rvm ruby-1.8.7-p160 #switch to the specified version
$ ruby -v
ruby 1.8.7(2009-04-08 patchlevel 160)[i686-darwin9.8.0]
$ gem install rails #note I'm not using sudo since the new gem paths point to the user's home directory
$ rvm ruby-1.9.1#switch to the specified version
$ ruby -v
ruby 1.9.1p376 (2009-12-07 revision 26041)[i386-darwin9.8.0]
$ gem install rails #note I'm not using sudo since the new gem paths point to the user's home directory
And that’s it, just go on and install rails, merb, sinatra or whatever rocks your boat!
rvm will work with MRI/YARV, JRuby, Ruby EE and Rubinius. Enjoy and don’t forget to check rvm’s website for the complete documentation!
Yesterday I’ve done something I should do more often: Revisit some code written a while ago for our current project and make it better.
Let’s face it. We all write crappy code the 1st time. The difference is in what we do about it afterwards.
We might decide it’s good enough and keep moving, or we could (and should!) stop and refactor it!
The code I revisited worked as a refactoring exercise and it’s initial version is shown below:
I’ll be speaking at this year’s Rails Summit Latin America in Sao Paulo, Brazil. It will be a good opportunity to meet some amazing people and visit friends back home!
Overall I’ll be spending 12 days in Brazil, with 2 of them dedicated to the conference. The other 10 I’ll be in Rio de Janeiro visiting my family and friends. I strongly advise you to spend some time in Rio too, if at all possible. It’s an amazing city and you can contact me if you have any questions.
Back to the conference, my session is called JRuby in the enterprise world: Using Rails with legacy code, and will be given in the form of a tutorial. I will walk you through some problems we had while making this kind of integration at my company, focusing mostly on dependency management.
At the end I hope you’ll have a good understanding of what JRuby is capable of in a legacy environment.
If you’re planning to attend and would like to hear anything specific about JRuby, please let me know, I can try and squeeze in.
We haven’t had really decided what to do until a few days before the competition, but I had this really simple idea and decided to go with it. Seems people liked it, given a few positive comments we received.
So, after 48 hours - which were not used to work full-time in the application - The Bird Watcher was born.
The Bird Watcher is a simple way to show the world what’s going on on Twitter for any topic you define. Go ahead and take a look at the website to see a live example.
We’re planning to keep the service up after the competition is over and we have some nice features lined up to go live on the next release.
In short, it was an interesting weekend and showed me that this team works really well together.
First off, I’d like to thank everyone who voted on this poll.
With a total of 236 votes, here is the summary of the first two questions:
- Are you currently working with or researching about language alternatives for the JVM? - e.g. JRuby, Scala, Groovy
Level of interest on JVM language alternatives
- If you answered yes or maybe to the previous question, what alternative would that be?
JVM language alternatives preference
As you can see, the vast majority of Java developers that participated on this poll have interest or are working with a language other than Java for the JVM. The results of the second chart were surprising for me and we have Groovy standing really tall with an astonishing 101 votes, followed by Scala and JRuby in a tougher competition.
The poll also consisted of 2 other questions, both free text, and I tried to analyze them in more detail to understand the “why’s” and “how’s” of these results.
Do you know?
I didn’t. And started to get annoyed by using these terms interchangeably and not really knowing the difference.
There are a few. And they are subtle. I don’t think most of us would ever have problems with it but it’s the kind of information you’ll be glad to know when having those weird behaviors in your code on a Friday at 6:01 pm, just before pushing to production.
I guess blocks are the most widely used term in the ruby community and there is little mistake on when to use it:
[1,2,3].eachdo|x|puts x*2end
The code between do and end is a block.
What’s important to keep in mind is that Procs behave like blocks whereas lambdas behave like methods. To understand what that means, I highlighted a couple of examples:
- The return keyword
I mentioned Procs behave just like blocks and as such, the return keyword abide to the same rules. This means, for instance, that the latest puts statement on the following code snippet, will never run:
For blocks - and procs-, return means “return from the calling method”, my_proc in this case. That’s why you don’t get to see the output of the puts statement.
On the other hand, in the lambda’s example, we get the opposite behavior:
def my_lambda(x)p = lambda{puts x*2; return}p.callputs"After calling proc"#This time, we reach this pointend
my_lambda(10)>>20>>After calling proc
Here, return says “return from the enclosing iterator”, which, in this case, just returns from the block and continnues the execution of the my_lambda method.
- Argument assignment
On to this second difference, procs and lambdas get more interesting when you can call them with arguments. And that’s when another subtle difference between them comes in.
I’ll start again with a proc:
p = Proc.new{|x,y|puts x, y}p.call>>nil
>>nil
p.call(1)>>1>>nil
p.call(1,2)>>1>>2p.call(1,2,3)>>1>>2p.call([1,2])>>1>>2
See how procs are flexible? They basically won’t complain if you do not provide parameters, provide extra parameters or even send an array as an argument where, as seen in the code above, it unpacks the array and assign its values to the correct variables.
As you’re probably guessing, lambdas behave like methods and are much less flexible:
l = lambda{|x,y|puts x, y}
l.call>>ArgumentError: wrong number of arguments (0for2)
l.call(1)>>ArgumentError: wrong number of arguments (1for2)
l.call(1,2)>>1>>2
l.call(1,2,3)>>ArgumentError: wrong number of arguments (3for2)
l.call([1,2])>>ArgumentError: wrong number of arguments (1for2)
Ruby 1.9 tip
Despite its name, Kernel.proc returns a lambda in Ruby 1.8. This has been fixed in Ruby 1.9. You actually get a Proc back.