[ANN] Rails 3.1.1.rc2

Hi everyone,

Rails 3.1.1.rc2 has been released. Please give it a try, it’s our chance to fix regressions you might find and make a beautiful 3.1.1 stable release. If there are no regressions I will be releasing 3.1.1 final next October 3rd. If you find any regression please contact me ASAP by email, twitter or github.

## CHANGES

*ActionMailer*

* No changes

*ActionPack*

* Allow asset tag helper methods to accept :digest => false option in order to completely avoid the digest generation.
Useful for linking assets from static html files or from emails when the user
could probably look at an older html email with an older asset. [Santiago Pastorino]

* Don’t mount Sprockets server at config.assets.prefix if config.assets.compile is false. [Mark J. Titorenko]

* Set relative url root in assets when controller isn’t available for Sprockets (eg. Sass files using asset_path). Fixes #2435 [Guillermo Iguaran]

* Fix basic auth credential generation to not make newlines. GH #2882

* Fixed the behavior of asset pipeline when config.assets.digest and config.assets.compile are false and requested asset isn’t precompiled.
Before the requested asset were compiled anyway ignoring that the config.assets.compile flag is false. [Guillermo Iguaran]

* CookieJar is now Enumerable. Fixes #2795

* Fixed AssetNotPrecompiled error raised when rake assets:precompile is compiling certain .erb files. See GH #2763 #2765 #2805 [Guillermo Iguaran]

* Manifest is correctly placed in assets path when default assets prefix is changed. Fixes #2776 [Guillermo Iguaran]

* Fixed stylesheet_link_tag and javascript_include_tag to respect additional options passed by the users when debug is on. [Guillermo Iguaran]

* Fix ActiveRecord#exists? when passsed a nil value

* Fix assert_select_email to work on multipart and non-multipart emails as the method stopped working correctly in Rails 3.x due to changes in the new mail gem.

*ActiveModel*

* Remove hard dependency on bcrypt-ruby to avoid make ActiveModel dependent on a binary library.
You must add the gem explicitly to your Gemfile if you want use ActiveModel::SecurePassword:

gem ‘bcrypt-ruby’, ‘~> 3.0.0’

See GH #2687. [Guillermo Iguaran]

*ActiveRecord*

* Add deprecation for the preload_associations method. Fixes #3022.

[Jon Leighton]

* Don’t require a DB connection when loading a model that uses set_primary_key. GH #2807.

[Jon Leighton]

* Fix using select() with a habtm association, e.g. Person.friends.select(:name). GH #3030 and
#2923.

[Hendy Tanata]

* Fix belongs_to polymorphic with custom primary key on target. GH #3104.

[Jon Leighton]

* CollectionProxy#replace should change the DB records rather than just mutating the array.
Fixes #3020.

[Jon Leighton]

* LRU cache in mysql and sqlite are now per-process caches.

* lib/active_record/connection_adapters/mysql_adapter.rb: LRU cache
keys are per process id.
* lib/active_record/connection_adapters/sqlite_adapter.rb: ditto

* Database adapters use a statement pool for limiting the number of open
prepared statments on the database. The limit defaults to 1000, but can
be adjusted in your database config by changing ‘statement_limit’.

* Fix clash between using ‘preload’, ‘joins’ or ‘eager_load’ in a default scope and including the
default scoped model in a nested through association. (GH #2834.) [Jon Leighton]

* Ensure we are not comparing a string with a symbol in HasManyAssociation#inverse_updates_counter_cache?.
Fixes GH #2755, where a counter cache could be decremented twice as far as it was supposed to be.

[Jon Leighton]

* Don’t send any queries to the database when the foreign key of a belongs_to is nil. Fixes
GH #2828. [Georg Friedrich]

* Fixed find_in_batches method to not include order from default_scope. See GH #2832 [Arun Agrawal]

* Don’t compute table name for abstract classes. Fixes problem with setting the primary key
in an abstract class. See GH #2791. [Akira Matsuda]

* Psych errors with poor yaml formatting are proxied. Fixes GH #2645 and
GH #2731

* Use the LIMIT word with the methods #last and #first. Fixes GH #2783 [Damien Mathieu]

*ActiveResource*

* No changes

*ActiveSupport*

* Fixed performance issue where TimeZone lookups would require tzinfo each time [Tim Lucas]

* ActiveSupport::OrderedHash is now marked as extractable when using Array#extract_options! [Prem Sichanugrist]

*Railties*

* Add jquery-rails to Gemfile of plugins, test/dummy app needs it. Closes #3091. [Santiago Pastorino]

* `rake assets:precompile` loads the application but does not initialize it.

To the app developer, this means configuration add in
config/initializers/* will not be executed.

Plugins developers need to special case their initializers that are
meant to be run in the assets group by adding :group => :assets.

You can find an exhaustive list of changes on [github](https://github.com/rails/rails/compare/v3.1.0…v3.1.1.rc2). Along with the [closed issues marked for v3.1.1](https://github.com/rails/rails/issues?milestone=6&state=closed). You can also take a look to what’s new between [v3.1.1.rc1 and v3.1.1.rc2](https://github.com/rails/rails/compare/v3.1.1.rc1…v3.1.1.rc2)

You can also see issues [we haven’t closed yet](https://github.com/rails/rails/issues?milestone=8&state=open).

Thanks to everyone!

Ruby 1.9.3 and 1.9.4, Rubydoc-beta, and queueing

In this episode, Peter and Jason talk about some upcoming releases of Ruby and the new release candidate, performance and monitoring, and some noteworthy new queueing systems.

Python and Django on Heroku

Python has joined the growing ranks of officially-supported languages on Heroku’s polyglot platform, going into public beta as of today. Python is the most-requested language for Heroku, and it brings with it the top-notch Django web framework.

As a language, Python has much in common with Ruby, Heroku’s origin language. But the Python community has its own unique character. Python has a culture which finds an ideal balance between fast-moving innovation and diligent caution. It emphasizes readability, minimizes "magic," treats documentation as a first-class concern, and has a traditon of well-tested, backward-compatible releases in both the core language and its ecosystem of libraries. It blends approachability for beginners with maintainability for large projects, which has enabled its presence in fields as diverse as scientific computing, video games, systems automation, and the web.

Let’s take it for a spin on Heroku.

Heroku/Python Quickstart

Make a directory with three files:

app.py

import os
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello from Python!"

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 5000))
    app.run(host='0.0.0.0', port=port)

requirements.txt

Flask==0.7.2

Procfile

web: python app.py

Commit to Git:

$ git init
$ git add .
$ git commit -m "init"

Create an app on the Cedar stack and deploy:

$ heroku create --stack cedar
Creating young-fire-2556... done, stack is cedar
http://young-fire-2556.herokuapp.com/ | git@heroku.com:young-fire-2556.git
Git remote heroku added

$ git push heroku master
Counting objects: 5, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (5/5), 495 bytes, done.
Total 5 (delta 0), reused 0 (delta 0)

-----> Heroku receiving push
-----> Python app detected
-----> Preparing virtualenv version 1.6.1
       New python executable in ./bin/python2.7
       Also creating executable in ./bin/python
       Installing setuptools............done.
       Installing pip...............done.
-----> Installing dependencies using pip version 1.0.1
       Downloading/unpacking Flask==0.7.2 (from -r requirements.txt (line 1))
       ...
       Successfully installed Flask Werkzeug Jinja2
       Cleaning up...
-----> Discovering process types
       Procfile declares types -> web
-----> Compiled slug size is 3.5MB
-----> Launching... done, v2
       http://young-fire-2556.herokuapp.com deployed to Heroku

To git@heroku.com:young-fire-2556.git
 * [new branch]      master -> master

Then view your app on the web!

$ curl http://young-fire-2556.herokuapp.com/
Hello from Python!

Dev Center: Getting Started with Python on Heroku/Cedar

All About Python

Created by Guido van Rossum in 1991, Python is one of the world’s most popular programming languages, and finds application in a broad range of uses.

Cutting-edge communities, like Node.js and Ruby, encourage fast-paced innovation (though sometimes at the cost of application breakage). Conservative communities, like Java, favor a more responsible and predictable approach (though sometimes at the expense of being behind the curve). Python has managed to gracefully navigate a middle path between these extremes, giving it a respected reputation even among non-Python programmers. The Python community is an island of calm in the stormy seas of the programming world.

Python is known for its clearly-stated values, outlined in PEP 20, The Zen of Python. "Explicit is better than implicit" is one example (and a counterpoint to "Convention over configuration" espoused by Rails). "There’s only one way to do it" is another (counterpointing "There’s more than one way to do it" from Perl). See Code Like a Pythonista: Idiomatic Python for more.

The Python Enhancement Proposal (PEP) brings a structured approach to extending the core language design over time. It captures much of the value of Internet standard bodies procedures (like Internet Society RFCs or W3C standards proposals) without being as heavy-weight or resistant to change. Again, Python finds a graceful middle path: neither changing unexpectedly at the whim of its lead developers, nor unable to adapt to a changing world due to too many approval committees.

Documentation is one of Python’s strongest areas, and especially notable because docs are often a second-class citizen in other programming languages. Read the Docs is an entire site dedicated to packaging and documentation, sponsored by the Python Software Foundation. And the Django book defined a whole new approach to web-based publishing of technical books, imitated by many since its release.

Frameworks and the Web

In some ways, Python was the birthplace of modern web frameworks, with Zope and Plone. Concepts like separation of business and display logic via view templating, ORMs for database interaction, and test-driven development were built into Zope half a decade before Rails was born. Zope never had the impact achieved by the later generation of frameworks, partially due to its excessive complexity and steep learning curve, and partially due to simply being ahead of its time. Nevertheless, modern web frameworks owe much to Zope’s pioneering work.

The legacy of Zope’s checkered history combined with the Python community’s slow recognition of the importance of the web could have been a major obstacle to the language’s ongoing relevance with modern developers, who increasingly wanted to build apps for the web. But in 2005, the Django framework emerged as a Pythonic answer to Rails. (Eventually, even Guido came around.)

Django discarded the legacy of past Python web implementations, creating an approachable framework designed for rapid application development. Django’s spirit is perhaps best summarized by its delightful slogan: "the web framework for perfectionists with deadlines." Where Rails specializes on CRUD applications, Django is best known for its CMS capabilities. It has an emphasis on DRY (Don’t Repeat Yourself). The Django community prefers to create reusable components or contribute back to existing projects over single-use libraries, which helps push the greater Python community forward. While Django is a batteries-included framework, the loose coupling of components allows flexibility and choice.

Other frameworks have found traction as well. Flask, a Sinatra-like microframework, makes use of Python’s decorators for readability. Pyramid emerged from the earlier Pylons and TurboGears projects, and their documentation already offers excellent instructions for deploying to Heroku.

Similarly, Python established a pattern for webserver adapters with WSGI. Many other languages have since followed suit, such as Rack for Ruby, Ring for Clojure, and PSGI/Plack for Perl.

In the Wild

Perhaps most striking about Python is the breadth of different realms it has taken root in. A few examples:

  • Science and math computing, evidenced by books and the SciPy libraries and conferences.
  • Video games, as seen in libraries such as PyGame and Cocos2d.
  • As an embedded scripting / extension language, in software such as Blender3D, Civilization IV, and EVE Online (via Stackless Python).
  • Major Linux distributions use Python for their system tools, such as yum and the Red Hat Network client for Red Hat and Fedora; or almost all of the GUI configuration and control panels on Ubuntu.
  • It’s one of the three official languages used by Google, alongside Java and C++.
  • And of course, internet startups: Reddit, Youtube, Disqus, Dropbox, and countless others use Python to build their businesses.

Conclusion

We anticipate that Python will be one of the most-used languages on the Heroku platform, and are overjoyed to welcome our Python brothers and sisters into the fold.

Special thanks to all the members of the Python community that helped with alpha testing, feedback, and patches on Heroku’s Python support, including: David Cramer, Ben Bangert, Kenneth Love, Armin Ronacher, and Jesse Noller.

We’ll be sponsoring and speaking at PyCodeConf next week. Come chat with us about what you’d like to see out of Python on Heroku!

Further reading:

Cutting An Agile Groove Videos; Help Wanted at PragProg.com

Cutting An Agile Groove Video Series; Help Wanted at PragProg.com

#285 Spork

Spork improves the loading time of your test suite by starting up your Rails application once in the background. Use it with Guard for the ultimate combo in fast feedback while doing TDD.

Ruby Programming 28th Batch: Registrations now open

Registrations are now open for RubyLearning’s popular Ruby programming course. This is an intensive, online course for beginners that helps you get started with Ruby programming.

Here is what Sandra Randall (Butler), a participant who just graduated, has to say – “You kindly offered me the opportunity to join your Ruby course. I’m new to development and found the course, even though basic for programmers, a little tricky for me. I managed to complete all of the assessments and really learnt a lot. Thank you very much for the opportunity. It has really given me the push I needed to learn Ruby and I’m currently treading my way through both the pickaxe and Agile Development books and enjoying it. I’ve recently been offered a position as a Junior Systems Developer at a local Software house in South Africa – all thanks to the push you gave me which gave me the motivation and drive to get going.”

What’s Ruby?

Ruby

According to http://www.ruby-lang.org/en/ – “Ruby is a dynamic, open source programming language with a focus on simplicity and productivity. Ruby’s elegant syntax is natural to read and easy to write.”

Yukihiro Matsumoto, the creator of Ruby, in an interview says –

I believe people want to express themselves when they program. They don’t want to fight with the language. Programming languages must feel natural to programmers. I tried to make people enjoy programming and concentrate on the fun and creative part of programming when they use Ruby.

What Will I Learn?

In the Ruby programming course, you will learn the essential features of Ruby that you will end up using every day.

Depending on participation levels, we throw a Ruby coding challenge in the mix, appropriate for the level we are at. We have been known to give out a prize or two for the ‘best’ solution.

Who’s It For?

A beginner with some knowledge of programming..

You can read what past participants have to say about the course. Click here.

Mentors

Satish Talim, Michael Kohl, Satoshi Asakawa, Victor Goff III and others from the RubyLearning team.

Dates

The course starts on Saturday, 29th Oct. 2011 and runs for seven weeks.

RubyLearning’s IRC Channel

Most of the mentors and students hang out at RubyLearning’s IRC (irc.freenode.net) channel (#rubylearning.org) for both technical and non-technical discussions. Everyone benefits with the active discussions on Ruby with the mentors.

How do I register and pay the course fees?

  • The course is based on the The Ultimate Guide to Ruby Programming eBook. This book is normally priced at US$ 19.95 and we are discounting it US$ 10.00 by combining it in the Course+eBook option below.
  • You can pay either by Paypal or send cash via Western Union Money Transfer or by bank transfer (if you are in India). The fees collected helps RubyLearning maintain the site, this Ruby course, the Ruby eBook, and provide quality content to you.
  • Once you pay the fees below, register on the RubyLearning.org site and send us your name and registered email id while creating an account at RubyLearning.org to satish [at] rubylearning [dot] com
  • We will enroll you into the course. If you have purchased the eBook at the time of registration, we will personally email you the eBook within 24 hours.

You can pay the Course Fees by selecting your option from the menu below (please select your option).

Register

At the end of this course you should have all the knowledge to explore the wonderful world of Ruby on your own.

Here are some details on how the course works:

Important:

Once the course starts, you can login and start with the lessons any day and time and post your queries in the forum under the relevant lessons. Someone shall always be there to answer them. Just to set the expectations correctly, there is no real-time ‘webcasting’.

Methodology:

  • The Mentors shall give you URL’s of pages and sometimes some extra notes; you need to read through. Read the pre-class reading material at a convenient time of your choice – the dates mentioned are just for your guideline. While reading, please make a note of all your doubts, queries, questions, clarifications, comments about the lesson and after you have completed all the pages, post these on the forum under the relevant lesson. There could be some questions that relate to something that has not been mentioned or discussed by the mentors thus far; you could post the same too. Please remember that with every post, do mention the operating system of your computer.
  • The mentor shall highlight the important points that you need to remember for that day’s session.
  • There could be exercises every day. Please do them.
  • Participate in the forum for asking and answering questions or starting discussions. Share knowledge, and exchange ideas among yourselves during the course period. Participants are strongly encouraged to post technical questions, interesting articles, tools, sample programs or anything that is relevant to the class / lesson. Please do not post a simple "Thank you" note or "Hello" message to the forum. Please be aware that these messages are considered noises by people subscribed to the forum.

Outline of Work Expectations:

  1. Most of the days, you will have exercises to solve. These are there to help you assimilate whatever you have learned till then.
  2. Some days may have some extra assignments / food for thought articles / programs
  3. Above all, do take part in the relevant forums. Past participants will confirm that they learned the best by active participation.

Some Commonly Asked Questions

  • Qs. Is there any specific time when I need to be online?
    Ans. No. You need not be online at a specific time of the day.
  • Qs. Is it important for me to take part in the course forums?
    Ans. YES. You must Participate in the forum(s) for asking and answering questions or starting discussions. Share knowledge, and exchange ideas among yourselves (participants) during the course period. Participants are strongly encouraged to post technical questions, interesting articles, tools, sample programs or anything that is relevant to the class / lesson. Past participants will confirm that they learned the best by active participation.
  • Qs. How much time do I need to spend online for a course, in a day?
    Ans. This will vary from person to person. All depends upon your comfort level and the amount of time you want to spend on a particular lesson or task.
  • Qs. Is there any specific set time for feedback (e.g., any mentor responds to me within 24 hours?)
    Ans. Normally somebody should answer your query / question within 24 hours.
  • Qs. What happens if nobody answers my questions / queries?
    Ans. Normally, that will not happen. In case you feel that your question / query is not answered, then please post the same in the thread – “Any UnAnswered Questions / Queries”.
  • Qs. What happens to the class (or forums) after a course is over? Can you keep it open for a few more days so that students can complete and discuss too?
    Ans. The course and its forum is open for a month after the last day of the course.

Remember, the idea is to have fun learning Ruby.

Technorati Tags: , , ,

Mike “launches” Uncrunched

My good pal Mike has a new blog at uncrunched.com. Check it out.

Facebook Open Graph Momentum

It’s been an exciting 24 hours for social application developers. A week ago, Facebook and Heroku announced a partnership to make it incredibly easy to get a live Facebook app running on Heroku. Yesterday at f8, Facebook unveiled the Timeline and the next generation of social apps on the Open Graph, with support for actions and objects.

The response has been amazing, and Heroku has seen more than 33,800 new apps created via Facebook in the last 24 hours; that’s more than 20 a minute. Facebook has again innovated and captured the excitement of the developer community.

To help developers understand and become productive with new Open Graph features, Facebook posted a great screencast this morning. Check it out and learn how to build the next generation of Open Graph apps.

Today Heroku is at the Facebook f8 Hack event, hanging out with a few hundred developers who are banging out new apps on Heroku. We can’t wait to see what amazing apps come out of it.

Be Prepared for Ruby 1.9.3 and 1.9.4: What’s New and What’s Different

On August 1, 2011, Ruby 1.9.3 preview 1 was released. The final version isn’t yet out (as of September 23) but Ruby 1.9.3 is going to be the next, full production-level release of MRI Ruby. But what’s the deal with 1.9.3 (and its successors, Ruby 1.9.4 and 2.0)? Keep reading!

The Summary

Ruby 1.9.3 is a relatively minor improvement on the Ruby 1.9.2 we already know and love. In short:

  • a focus has been placed on performance with file loading, File and Pathname all significantly improved
  • Ruby 1.9.2 mostly fixed down the language specification for 1.9; 1.9.3 is mostly work on a ‘better implementation’
  • you can tune the garbage collector via environment variables (more on this in a post coming soon!)
  • Ruby’s license changes from dual Ruby + GPLv2 to dual Ruby + 2-clause BSD
  • improved GC performance with a lazy garbage collector
  • a ‘better strategy’ for the GIL / GVL
  • test/unit supports parallel testing
  • Random.rand tweaks (and rand() now accepts ranges)
  • io/console, a new library in the stdlib
  • 4 new encodings (so far) – cp950, cp951, UTF-16, and UTF-32
  • extra String methods
  • a number of tweaks to formatting strings
  • a smattering of other bits and pieces, but this is the TLDR overview!

For some examples of the above, however, read on.

Yuki ‘yugui’ Sonoda on Ruby 1.9.3

At RubyConf Taiwan (held August 26-27, 2011), core team member Yuki ‘yugui’ Sonoda gave a talk called Ruby 1.9.3 and Ruby 1.9 Development which outlined her current thinking on Ruby 1.9.3, Ruby 1.9.4, and Ruby 2.0. It’s not very long and worth a watch.

You can watch the video on Vimeo or see the slides on SlideShare. Alternatively, you may see the video embedded above.

Yugui’s talk was only short but the key points were that:

  • Ruby 1.9.2 essentially fixed down the language design for 1.9; 1.9.3 is just a ‘better implementation’
  • Ruby 1.8 has “no future” (she stated this a few times) but it will be “supported” for a few years to come
  • there is no intention to release a Ruby 1.8.8
  • “You need to switch to Ruby 1.9”
  • Ruby 1.9.3 will be out very soon
  • the license was changed to joint BSD because the release of GPLv3 forced a rethink on licensing
  • the locking strategy related to the GIL / GVL has been improved, resulting in improved performance
  • test/unit’s parallelization features are well suited for testing Ruby’s stdlibs more quickly
  • you can “safely switch to Ruby 1.9.3 from Ruby 1.9.2” as there are “few incompatibilities”
  • the new “lazy GC” will improve the response time of the garbage collector and decrease overall GC throughput – more info in this article, for the curious
  • Yugui is not particularly familiar with RubySpec – it seems to continue to not be a focus for core MRI implementers

A Selection of 1.9.3 Changes

I’ve cherry picked a few changes in 1.9.3 to highlight.

Faster loading – the load.c patch

Recently, I wrote all about the load.c file loading performance saga in Ruby 1.9.2. These issues have begun to be addressed and a nifty patch has enabled Ruby 1.9.3 to post significantly improved loading times for apps with large trees of files to load. You could see anywhere from a 5% to 40% reduction in load times for your apps.

Time#strftime supports %:z and %::z

Time.now.strftime("%:z %::z")  # => "+01:00 +01:00:00"

Time#strftime now supports some extended formats for timezones. :z includes the minutes and ::z gives the full HH:MM::SS.

String#prepend and String#byteslice

Among some changes to the String class are a couple of new methods. First, prepend:

a = 'world'; a.prepend('hello '); a  # => "hello world"

String#prepend prepends one string to another, in-place. The result is equivalent to using a[0,0], in this case.

Next, byteslice will let you get access to sections of a string at the byte (rather than character) level:

a = 'hello'; a.byteslice(2, 2)  # => "ll"

New character encodings

CP950, CP951, UTF-16, and UTF-32 encodings have been added. Previously, UTF-16 and UTF-32 were available in big-endian (BE) and little-endian specific forms. For example: Encoding.find("UTF-16LE"). I have not yet confirmed if the new UTF-16 and UTF-32 encodings support the byte ordering marks that they should, but am currently assuming so. CP950 and CP951 are Microsoft encodings for Chinese character sets.

Changes to ‘Random’

The Random class now accepts ranges on its rand class method. In 1.9.2, this was only allowed on its instance method. For example:

Random.rand(5..9)   # => [a number between 5 and 9]

A side effect of this is that Kernel.rand now also supports ranges in 1.9.3. For example:

rand(5..9)  # => [a number between 5 and 9]

#__id__ moved from Object to BasicObject

BasicObject is the new grand-daddy of the inheritance tree in Ruby 1.9 and in 1.9.3 it gains access to the functionality of the object_id method by way of __id__ which has been moved into BasicObject from Object. This may help those of you using BasicObject for delegators, proxies, and the like.

BasicObject.new.__id__   # => 2152881920

More?

If you want to pick up on more changes, see the Ruby 1.9.3 NEWS document or, perhaps, check out my Ruby 1.9 Walkthrough screencast ($16) which has an entire section dedicated to things that are new in Ruby 1.9.3.

The Future: Ruby 1.9.4

In her talk, Yugui mentioned two extra production releases of Ruby to come after Ruby 1.9.3. The first was unnamed and was said to be a 1.9 release with minor language changes to 1.9.2/3. In the Q&A, someone asked Yugui if this would be called Ruby 1.9.4 but she said it was still under discussion but hoped it would be called 1.9.4. This unnamed next release would, however, have complete backwards compatibility for code written in Ruby 1.9.2/3.

The Future: Ruby 2.0!

The second release after 1.9.3 “should be called Ruby 2.0”, however. It will have significant changes but Yugui notes that “it should be comfortable with 1.9.3” and that you should be able to “safely switch” to 2.0, indicating that any significant changes wouldn’t involve removing core language elements or permanently changing core syntax features.

It has previously been said, however, that Ruby 2.0 could be “several years” away, so don’t get too excited about this yet. Now is the time to start weighing if you want to influence Ruby 2.0’s design, however!

Still getting to grips with Ruby 1.9? Try my walkthrough

I recently released a screencast called Ruby 1.9 Walkthrough, a mega walkthrough of what’s new in Ruby 1.9.2 (and Ruby 1.9.3) from the perspective of Ruby 1.8.7. If you’re still primarily a Ruby 1.8 based developer and aren’t entirely sure about what’s new in Ruby 1.9, check it out.

Ruby 1.9 Walkthrough, Cross domain ajax in Ruby, Arrrcamp

In this episode, Peter talks about his new product, a Ruby 1.9 screencast series, and we go over upcoming conferences, cross domain ajax in Ruby, and more.

Technical Blogging in beta; Podcast on CoffeeScript

Technical Blogging: Turn Your Expertise into a Remarkable Online Presence in beta; Podcast with Trevor Burnham on CoffeeScript

The Ruby 1.9 Walkthrough: The Ultimate Ruby 1.9 Primer for 1.8 Developers

In a presentation about Ruby 1.9.3, Yuki Sonoda notes that Ruby 1.8 has “no future” and its “end of life” is being discussed pretty seriously. Ruby 1.8 is becoming history, but what’s the alternative? Why, Ruby 1.9! 🙂

Even amongst the groups I’m involved with, I’ve seen a lot of resistance to Ruby 1.9. Sometimes it’s because of deployment or library concerns, but often there’s a hesitancy over what’s changed, what’s new, or what has been flat out removed from 1.9. So I’ve been working on something to help out.. because I think Ruby 1.9 is awesome and everyone should be taking it seriously ASAP.

Presenting.. the Ruby 1.9 Walkthrough

The Ruby 1.9 Walkthrough is an extended-length screencast that walks you through what’s new, gone, or plain different in Ruby 1.9.2 and 1.9.3 vs 1.8. It’s everything you wanted to know about 1.9 but were afraid to ask 🙂 (There’s a short sample there too if you want to get a feel for it.)

It’s only $24 and you get a 3 hour video organized into logical sections which you can either watch straight through or jump around at your pleasure. In due course, I’ll also be wrapping up my notes with more sample code into a PDF version to send to everyone, but that’s still a little ways off (though you can enjoy my rather scrappy notes if you like).

Some of What You’ll Learn

My notes came to almost 500 lines in all but here’s a snapshot of what’s covered:

  • How proc and lambda behavior differs significantly from 1.8
  • How to wrestle with character encodings like UTF-8 (and issues to be aware of when upgrading old apps)
  • The new and differing ways to check range membership
  • How old Ruby 1.9 is and where it has descended from
  • New tricks and techniques opened up by the awesome new Oniguruma-based regular expression engine
  • The new MiniTest::Unit and MiniTest::Spec libraries
  • Quickly calling system library functions with Fiddle
  • Code coverage utilities right in the stdlib
  • Extensions to splat (*) behavior in 1.9
  • New hash syntax and key changes to hash methods
  • The 3 different encoding types in 1.9 and why each is important
  • What fibers are, how they compare to threads, and how threads have changed
  • Why Proc#=== makes sense as a way to call procs.. sometimes
  • 1.9.3 specific updates (stuff that’s not even in 1.9.2!)
  • How to tweak the garbage collector in 1.9.3
  • .. and I’ve barely scratched the surface!

The Full Contents

Here are the main sections of the video (along with their starting time):

  • 00h 00m — Introduction from Peter Cooper
  • 00h 04m — Ruby 1.9’s history
  • 00h 11m — Alternative 1.9 Implementations
  • 00h 13m — Key Changes (Overview)
  • 00h 19m — Getting Ruby 1.9
  • 00h 21m — Strings
  • 00h 30m — Character Encoding
  • 00h 49m — Hashes
  • 00h 56m — Arrays
  • 01h 02m — Procs and Lambdas
  • 01h 16m — Blocks
  • 01h 20m — Enumerators and Enumerable
  • 01h 24m — Regular Expressions
  • 01h 35m — Threads
  • 01h 38m — Fibers
  • 01h 42m — Time
  • 01h 46m — Standard Library (New and Gone)
  • 02h 05m — New Syntax and Miscellaneous Elements
  • 02h 45m — Garbage Collection
  • 02h 50m — Ruby 1.9.3 Specifics

So check out The Ruby 1.9 Walkthrough. There’s a 5 minute sample MPEG 4 file you can download if you want to get a feel for it or check that the video format/codec suits you. (If you have problems though, you can always e-mail me. I have a special Apple TV version available on request too.)

This post also kicks off a short season of Ruby 1.9 related blog posts. I’m going to be going over specific elements of Ruby 1.9 syntax, changes, or additions here on Ruby Inside over the coming weeks. Ruby 1.9 is important and I’d love to see more people using it 🙂

How do I use Sinatra to access the Google+ API?

How do I use Sinatra to access the Google+ API?

RubyLearning is conducting many free, online courses on Google+. Some participants wanted an answer to their question “How do I use Sinatra to access the Google+ API?” This blog post explains the same. Read on.

Pre-requisite

Install Sinatra, Git, Heroku, Bundler

Refer RubyLearning’s article on Google+.

Create a folder on your hard disk

Create a folder sinatragplus. This is where we will store our Sinatra app. Open a Bash shell in this folder.

Create the following folders also

Folder for app

Organize your application

Static Files

Static files are served from the public folder. Note that the public folder name will not be included in the URL. A file ./public/stylesheets/style.css is made available as rubylearning.org/stylesheets/style.css. Do note that we can have any directory layout under the public folder.

Layout

We will soon create layout.erb file in the views folder. This allows the basic layout of our site headers, footers and navigation panes to be controlled independently. A change in layout.erb is instantly applied across our whole site.

Let’s look at a sample file:

<html>
  <head>..</head>
  <body>
    <%= yield %>
  </body>
</html>

In the above file, note the usage of yield. The file calls yield at the point you want the content to be included i.e. it refers to some .erb in the views folder and the results of that .erb are stuck at the place, where you called yield.

Now, let’s write our app’s layout.erb file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>A Sinatra app to access Google+</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="description" content="RubyLearning.org" />
    <meta name="keywords" content="rubylearning,ruby,ruby programming,ruby course,sinatra course" />
    <link rel="stylesheet" type="text/css" href="/stylesheets/style.css" />
    <link rel="icon" type="image/ico" href="/images/favicon.ico" />
  </head>
  <body>
    <%= yield %>
  </body>
</html>

Image

I am using a favicon (favicon.ico) for my app, which is stored in the public/images folder.

Stylesheet

We have our stylesheet namely style.css in the folder public/stylesheets.

body
{
  line-height: 1.6em;
}

h1 {
  color: #2A1959;
  border-bottom: 2px solid #2A1959;
}

h2 {
  color: #474B94;
  font-size: 1.2 em;
}

#footer {
  clear: both;
  border-top: 1px solid #2A1959;
  text-align: left;
  height: 50px;
  font-size: 70%;
  width: 100%;
}

#hor-minimalist-a
{
  font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
  font-size: 12px;
  background: #fff;
  margin: 45px;
  width: 480px;
  border-collapse: collapse;
  text-align: left;
}
#hor-minimalist-a th
{
  font-size: 14px;
  font-weight: normal;
  color: #039;
  padding: 10px 8px;
  border-bottom: 2px solid #6678b1;
}
#hor-minimalist-a td
{
  color: #669;
  padding: 9px 8px 0px 8px;
}
#hor-minimalist-a tbody tr:hover td
{
  color: #009;
}

View

A view is responsible for generating a user interface, normally based on data. For example, an online store will have a list of products to be displayed on a catalogue screen. The view accesses the data and formats it for the end-user.

All file-based views are looked up in the views folder.

Using ERB

ERB is written in pure Ruby and is included with the standard Sinatra distribution. ERB allows you to embed Ruby statements in an HTML page.

The important things to know about an .erb file is that <%= ruby_code %> evaluates the ruby code and outputs the result, and <% ruby_code %> evaluates the code, but doesn’t output anything.

We will use ERB for our app.

Note: If we write:

get '/' do
  erb :index
end

This tells Sinatra that when a GET request for ‘/’ comes in, that we should use the ERB helper to render the index.erb template, which is stored in the views sub-folder by convention and marked up with embedded Ruby (ERB).

Write the sinatragplus.rb app

Store sinatragplus.rb in the folder sinatragplus:

# sinatragplus.rb
require 'sinatra'
require 'google_plus'

error do
  erb :'500'
end

#class
class GPlus
  def initialize(apikey, gid)
    @apikey = apikey
    @gid = gid
    get_info
  end
  attr_reader :row0, :row1, :row2
  private
    #Get info about specific G+ ID
    def get_info
      # GooglePlus.api_key = 'Your API Key'
      begin
        GooglePlus.api_key = @apikey
        person = GooglePlus::Person.get(@gid.to_i)
        @row0 = person.display_name
        @row1 = person.tagline
        @row2 = person.url
      rescue Exception => msg
        # display the system generated error message
        puts msg
      end
    end
end

get '/' do
  erb :index
end

# Display Google+ details
post '/show' do
  @gplus = GPlus.new(params[:apikey], params[:gid])
  erb :show
end

Explanation

  • Install: gem install google_plus.
  • We are going to use the above installed google_plus gem.
  • To access the Google+ API, get your own Google API key.
  • Note down the Google+ ID of the person whose Google+ profile you want to display using this app. For example, here’s my Google+ URL and the number in the URL namely 107809992818057105754 is my Google+ ID.
  • When a GET request for ‘/’ comes in, we are going to render the index.erb template in the public/views folder.
  • The file index.erb has a HTML form that accepts the Google+ API key and ID for the user profile that you want to display. Note that even if you do not give any value to these fields, the app will not crash. Handler is the generic term that Sinatra uses for the “controllers”. A handler is the initial point of entry for new HTTP requests into your application. In handlers you can reach submitted form parameters directly via the params hash. Also note, that when you click on the submit button of the form a POST request is being sent.
  • The post '/show' do creates an object of our class GPlus passing to the initialize method the apikey and google id that your entered on the screen (via params). The initialize method in-turn calls a private method get_info that accesses the Google+ API and returns a person object We call the method display_name, tagline and url on the person object and populate instance variables @row0, @row1 and @row2.
  • The show.erb displays these values in a HTML table.

Error Handling

When someone comes to a page on your domain that is no longer there (either because it’s been deleted, because they’ve typed something in wrong or because the link that they followed was wrong) they are shown the dreaded 404 ‘page not found’ error page.

This error simply means that the person was able to communicate with your server but that the server couldn’t find the page that they were after.

404 errors should not be confused with “server not found” or similar errors, in which a connection to the destination server could not be made at all.

When a Sinatra::NotFound exception is raised, or the response’s status code is 404, the not_found handler is invoked:

Write 404.erb in the public/views folder. Note that I had to surround the erb :'404' in single quotes. This is because Ruby syntax doesn’t let symbol’s first character be a number. By quoting it, it gets around that issue.

A 500 error page will be thrown to the client when the Web server (running the Web Site) encounters an unexpected condition that prevents it from fulfilling the request by the client (e.g. your Web browser) for access to the requested URL.

By default error will catch Sinatra::ServerError. Sinatra will pass you the error via the ‘sinatra.error’ in request.env.

Write 500.erb in the public/views folder.

Our app is ready! Let’s deploy it to Heroku.

Create config.ru file in the folder sinatragplus

This file contains:

require './sinatragplus'
run Sinatra::Application

Install required gems for our app

In the Bash shell type:

$ bundle init

Edit the created Gemfile with your preferred text editor to let it look like this:

source "http://rubygems.org"
gem 'sinatra'
gem 'google_plus'

In the Bash shell type:

$ bundle check

Finally in the open Bash shell, type:

$ bundle install

Setup your local app to use Git

In the already open Bash shell, type:

$ git init
$ git add .
$ git commit -m "sinatragplus first commit"

Create the app on Heroku

In the bash shell, type:

$ heroku create

On my machine it showed:

Creating growing-fire-5252... done, stack is bamboo-mri-1.9.2
http://growing-fire-5252.heroku.com/ | git@heroku.com:growing-fire-5252.git
Git remote heroku added

Rename the app

$ heroku rename sinatragplus

Push your application to Heroku

$ git push heroku master

That’s it, the app is now running on Heroku! You can take a look at it, in your browser type: http://sinatragplus.heroku.com/.

What next?

On the person object use the attributes method to get all the person fields back as a Hash:

properties = person.attributes
properties.each { |key, value| puts "#{key} equals #{value}" }

Exercise

In show.erb I have populated only the display_name, tagline and url fields of person. Populate all the other person fields in the HTML table that is generated by show.erb.

Have fun!

Do post a link to your version of this program. Feel free to ask questions and give feedback in the comments section of this post. Fellow Rubyists, if you would like to write a guest blog post for RubyLearning email me at satish [at] rubylearning.org

Technorati Tags: , , , ,

Flex With Ruby on Rails talk – An AdobeMax preview

This is a presentation I gave in September 2011 at the Denver RIA Developers Group showing how to create a Flex application that interacts with a Ruby on Rails server. In fact it was schedule for the Flash Builder track of Adobe Max but was bumped to the the 360Flex Unconference as it was deemed too specialized for the general track. In this presentation I will show you how to interact with Rails using REST, nested resources, nested attributes and the newest kid on the block, the bulk-api allowing to transfer complex data structures between your rich client application and your Rails server. You will get a good overview on how Rails works and how to quickly build a Flex application on top of Ruby on Rails.

Flex With Ruby on Rails talk – An AdobeMax preview

This is a presentation I gave in September 2011 at the Denver RIA Developers Group showing how to create a Flex application that interacts with a Ruby on Rails server. In fact it was schedule for the Flash Builder track of Adobe Max but was bumped to the the 360Flex Unconference as it was deemed too specialized for the general track. In this presentation I will show you how to interact with Rails using REST, nested resources, nested attributes and the newest kid on the block, the bulk-api allowing to transfer complex data structures between your rich client application and your Rails server. You will get a good overview on how Rails works and how to quickly build a Flex application on top of Ruby on Rails.

Flex With Ruby on Rails talk – An AdobeMax preview

This is a presentation I gave in September 2011 at the Denver RIA Developers Group showing how to create a Flex application that interacts with a Ruby on Rails server. In fact it was schedule for the Flash Builder track of Adobe Max but was bumped to the the 360Flex Unconference as it was deemed too specialized for the general track. In this presentation I will show you how to interact with Rails using REST, nested resources, nested attributes and the newest kid on the block, the bulk-api allowing to transfer complex data structures between your rich client application and your Rails server. You will get a good overview on how Rails works and how to quickly build a Flex application on top of Ruby on Rails.

#284 Active Admin

Active Admin allows you to quickly build an admin interface with just a few commands. Not only does it look great, but it is very customizable as shown in this episode.

Improvements to Bundle Watcher

I just released an update to Bundle Watcher this morning that may make it a little easier to get your Ruby gem updates tracked. Now you can specify a URL where your Gemfile.lock resides, rather than having to upload a file.

You can also now see a list of bundles that your tracking, once you’ve logged in via Github. This list shows you at a glance which gems have been updated for your bundles.

Improvements to Bundle Watcher

I just released an update to Bundle Watcher this morning that may make it a little easier to get your Ruby gem updates tracked. Now you can specify a URL where your Gemfile.lock resides, rather than having to upload a file.

You can also now see a list of bundles that your tracking, once you’ve logged in via Github. This list shows you at a glance which gems have been updated for your bundles.

Improvements to Bundle Watcher

I just released an update to Bundle Watcher this morning that may make it a little easier to get your Ruby gem updates tracked. Now you can specify a URL where your Gemfile.lock resides, rather than having to upload a file.

You can also now see a list of bundles that your tracking, once you’ve logged in via Github. This list shows you at a glance which gems have been updated for your bundles.