Updates from August, 2008 Hide threads | Keyboard Shortcuts

  • jwz threading on GitHub 

    fdietz 9:20 pm on August 31, 2008 Permalink | Reply

    Just posted a preliminary version of my jwz threading library on GitHub. Took me the whole day to get a first project including complete set of Rake tests up and running.

    Since I’m still not sure if posting gems via GitHub is sufficient, I’ve registered a new project on RubyForge. They now support Git too, which makes it super easy to push my changes to both “hubs”. So, you will most probably be able to download some ruby gems soon!

    Now, that the setup phase is done I can concentrate on cleaning up my specs and getting the API design right.

     
    • Micah 4:52 pm on November 4, 2008 Permalink | Reply

      Hey,

      I just saw your jwz implementation on GitHub. I’m hoping to add mailing list functionality to my website, and I think your library could be a big help.

      I just wanted to thank you for putting it out there :)

    • fdietz 7:53 am on November 5, 2008 Permalink | Reply

      Hy Micah!

      and thanks for looking into it! I’m actually in the process of uploading a gem for it this week. So, it will be super easy for you to integrate into your project.

      Cheers,
      -Frederik

  • ActiveRecord Dynamic Finder – behind the scenes 

    fdietz 6:40 pm on August 26, 2008 Permalink | Reply

    Wanted to finally post more about the dynamic finders, but then found Jamis Buck’s blog entries which seems to be much better anyways than anything I would have been able to scribble down in my blog.

    http://weblog.jamisbuck.org/2006/11/20/under-the-hood-activerecord-base-find-part-2

    http://weblog.jamisbuck.org/2006/12/1/under-the-hood-activerecord-base-find-part-3

    Enjoy!

     
  • Symbol#to_proc and Ruby’s Open Classes 

    fdietz 2:03 pm on August 21, 2008 Permalink | Reply

    Just saw an article related to my last post about Symbol#to_proc. Very interesting read! And even more fun is this article which explains the same mechanism and currying on top:

    proc {|x, y, z| x + y + z }.curry
    

    returns the equivalent of:

    proc {|x| proc {|y| proc {|z| x + y + z } } }
    

    Here’s the example:

    plus_five = proc { |x,y,z| x + y + z }.curry.call(2).call(3)
    plus_five[10]  #=> 15
    

    I’ve seen something similar in Scala. A good explanation of Scala function currying can be found in Daniel Spiewak’s blog. BTW, Scala finally got a new website! And even better: Just got an E-Mail from Artima.com that the 4th edition of “Programming in Scala” arrived. Something to read for the weekend!

     
  • Symbol#to_proc – what? 

    fdietz 9:24 pm on August 12, 2008 Permalink | Reply

    While reading Advanced Rails by Brad Ediger, I’ve stumbled upon this little helper in ActiveSupport. The to_proc method is an extension to Symbol. Let me shamelessly copy Brad’s example here:

    (1..5).map { |i| i.to_s } # => ["1", "2", "3", "4", "5"]

    This is already pretty nice, but now look what happens when using Symbol#to_proc:

    (1..5).map(&:to_s) # => ["1", "2", "3", "4", "5"]

    This is even shorter and does produce exactly the same output. So what happened here?

    The “&” character tells Ruby that you want to call map with “to_s” as a block argument. It will force Ruby to call the Symbol’s to_proc method. The method will create a Proc and send the symbol to the object calling the to_proc method. And this leads to iterating over the numbers specified by the range and then calling the block, passing in the numbers and converting them to strings.

    Okay… This is a typical example of me not being able to figure out what some code actually means and then by accident finding the explanation somewhere else. How the heck am I supposed to know where to find the documentation to such a cool extensions? I will let you know when I’m finally able to solve this mystery…

     
    • Brad Ediger 3:15 am on August 13, 2008 Permalink | Reply

      Hi Frederik,
      I’m sort of in agreement with you that this little trick can decrease readability of code, depending on context. Symbol#to_proc is fairly idiomatic in Rails now, having been part of ActiveSupport for quite some time. It’s still something one has to learn as part of one’s Ruby “dialect”. And more often than not, I choose to explicitly write my procs out in Ruby code (outside of Rails), rather than importing Symbol#to_proc. The to_proc hack is also slower (sometimes substantially slower) in Ruby 1.8 / ActiveSupport because of the overhead of building the Proc.

      Incidentally, Ruby 1.9 includes Symbol#to_proc as part of the core language.

      Regards,
      Brad

    • fdietz 1:03 pm on August 13, 2008 Permalink | Reply

      Hi Brad,

      it seems generally more difficult in a dynamic languages like Ruby to figure out how things work. Meta-programming, reflection, coding by convention, etc. just means that one has to simply document things explicitly. So, I haven’t found a good way yet to find documentation for particular things and instead focused on reading a lot of books about Ruby in general and Ruby on Rails in particular. I’m wondering how we could improve such a situation, for example: how should we document “method_missing” inner workings with rdoc? If would be cool to find a way to formalize this a bit and come up with tooling support. Something like annotations in rdoc pointing to documentation would already be helpful, but I haven’t really thought about it yet. Should probably write a blog entry on this some time.

      Really like your book, keep up the good work!

      Cheers,
      -Frederik

  • Migrations and Foreign Key Handling 

    fdietz 10:21 am on August 3, 2008 Permalink | Reply

    A question which came up real quick was how to add a foreign key to your migrations. In my example rails app I’m using a project with a has_many association to tasks, like this:

    class Project < ActiveRecord::Base
      has_many :tasks
    end
    
    class Task < ActiveRecord::Base
      belongs_to :project
    end
    

    Now I want my task database to look like the following:

    mysql> describe tasks;
    +------------+--------------+------+-----+---------+
    | Field      | Type         | Null | Key | Default |
    +------------+--------------+------+-----+---------+
    | id         | int(11)      | NO   | PRI | NULL    |
    | title      | varchar(255) | YES  |     | NULL    |
    | body       | text         | YES  |     | NULL    |
    | status     | tinyint(1)   | YES  |     | NULL    |
    | created_at | datetime     | YES  |     | NULL    |
    | updated_at | datetime     | YES  |     | NULL    |
    | project_id | int(11)      | NO   | MUL | NULL    |
    +------------+--------------+------+-----+---------+
    7 rows in set (0.00 sec)

    Note, that I’ve removed the last “extra” column which is usually shown by the MySQL describe command. It only shows the auto_increment for the primary key but it would have overlapped my fixed-width wordpress theme.

    First we have to create a new migration for adding a new column using:

    script/generate migration add_project_column

    This will generate an initial ruby file where I only added the two lines to add and delete a column.

    class AddProjectColumn < ActiveRecord::Migration
      def self.up
        add_column :tasks, :project_id, :integer, :null => false
      end
    
      def self.down
        delete_column :tasks, :project_id
      end
    end
    

    Next step is the foreign key which we can put directly in the migration, like this:

    class AddProjectColumn < ActiveRecord::Migration
      def self.up
        add_column :tasks, :project_id, :integer, :null => false
    
        execute 'ALTER TABLE tasks ADD CONSTRAINT fk_tasks_projects FOREIGN KEY ( project_id ) references projects( id )'
      end
    
      def self.down
        delete_column :tasks, :project_id
    
        execute 'ALTER TABLE tasks DROP FOREIGN KEY fk_tasks_projects'
      end
    end
    

    Note, that I’m actually executing a MySQL command to add a foreign key. So, this code most probably won’t work when used with different databases.

    For now this is good enough, but I should probably look into refactoring these two lines by extracting them into a migration helper class. This way it will be easier to modify in a single central place in case the database will be changed.

    I’m still searching for database independent foreign key management handled in migrations. So, please let me know if you find a better way to do this! Until then some more readings

     
  • ActiveRecord dynamic attribute-based finders 

    fdietz 9:58 am on August 3, 2008 Permalink | Reply

    I’m more used to Java ORM frameworks as for example JPA and Hibernate but started to play around with ActiveRecord lately. Probably all has been said already and I will spare you the introduction and point you to some documentation instead. It took me some time to realize that there is much more than what is shown mostly in online articles, blog postings and books. 

    Let’s start with the typical example of a book model containing articles defined with a simple has_many relation.

    class Book < ActiveRecord::Base
      has_many :chapters
    end
    
    class Chapter < ActiveRecord::Base
      belongs_to :book
    end
    

    A typical query for all books would then look like this:

    Book.find(:all)
    

    and a query for all published books would be something similar to:

    Book.find(:all, :conditions => [ 'status = ?', false])
    

    Now to simplify this we can instead use the dynamic finder:

    Book.find_all_by_status(false)
    

    Until now this is pretty straightforward, but now comes the interesting part. Imagine now that you have got a book and you want to retrieve a list of chapters:

    @book = Book.find(params[:id])
    @chapters = @book.chapters.find_all_by_title(title)
    

    Notice how one can use the same dynamic finders directly on the child association? Much easier than making a query using the book_id foreign key in the chapters table! In fact, ActiveRecord automatically makes the class-level methods of the Chapter model available directly for the associations. This also works in case you have added your own finder methods in the model.

    class Chapter < ActiveRecord::Base
      belongs_to :book
    
      def self.find_finished
        Chapter.find_all_by_status(false)
      end
    end
    

    Note, the “self” since we are adding a class-level method to Chapter. ActiveRecord will automatically make this now available in the association:

    @chapters = @book.chapters.find_finished
    

    Hope you got the idea. It simply is beautiful. Next time we should probably look into what’s behind the dynamic finder method.

     
c
compose new post
j
next post/next comment
k
previous post/previous comment
r
reply
e
edit
o
show/hide comments
t
go to top
l
go to login
h
show/hide help
esc
cancel