Channels
Displaying page 7
Favorite
Posted 22 days ago at Ruby Quicktips

Coming from Java, it’s likely you share my simple “for-each-loop”-fixation:

tags              = ["ruby", "rails", "java"]
concatenated_tags = ""

tags.each { |tag| concatenated_tags << "#{tag}, " }

concatenated_tags # => "ruby, rails, java, "

#now, remove the unnecessary comma and space at the end
concatenated_tags.chop!.chop! # => "ruby, rails, java"

Ruby Arrays have a far more sophisticated function to solve the problem. Just use the join method and you’re done:

concatenated_tags = tags.join(', ') # => "ruby, rails, java"

This tip was submitted by Sven Kräuter.

back to top
Posted 22 days ago at The Geek Talk

Who is Kevin  Gisi?

Kevin W. Gisi is a software engineer, Eau Claire Ruby User Group co-founder, Rails Rumble administrator, open-source advocate, piano accompanist, and nice guy.

Where and when did you start programming?

My first experience programming was with a toy V-Tech laptop when I was little. There was a primitive BASIC interpreter, and a manual with a few games I could program in. Eventually I switched to the QBASIC interpreter I found on the Windows 98 CD, then a bit of TI-BASIC as I entered high school. I took some preliminary classes in Java and C++ in high school, and started to dive into Bash scripting on various Linux distributions. Halfway through college, I switched my major from music over to software engineering.

Why Ruby/Rails?

I personally got started with Ruby on Rails after I got a job on campus doing web development under Brian Hogan. Within six months, I had won an award for competing in the 48-hour Rails Rumble development competition. After that, I was hooked. Ruby is a language designed for programmer happiness, and Rails is a framework that so well optimizes the process of development that we can have events like the Rails Rumble. The idea of being able to create a minimum-viable-product within a 48-hour timespan is fascinating, and one of the reasons I try to help evangelize the language and framework.

What does your typical day look like?

My days vary depending on the activities I’m involved in, but I usually work from home. I occasionally grab lunch with some other local developers mid-day. I’ve been finishing up my workday at a local coffee shop recently, enjoying some free wifi before heading to community theatre rehearsal. Evenings vary for me – occasionally I’ll continue working if we have a deadline approaching. Otherwise, I may be working on some pet projects, or preparing a presentation, or just relaxing.

What do you do in your free time?

I’m reasonably involved with the local community theatre, as a performer and as a pianist. Beyond that, helping facilitate the ECRuby group, organizing the Rails Rumble, and working on my own open-source stuff takes up a fair bit of time.

Current favorite apps?

I’m a sucker for simplicity and good workflow management. Right now, I’m very impressed with CloudApp.

What OS do you prefer?

It’s really a toss-up between OS X Snow Leopard, and Ubuntu with the Ratpoison window manager. I love the flexibility of OS X, but you just can’t beat Ratpoison for managing focus.

Small picture for your Workplace?

Favorite: Color, Font, Language, JS Framework?

I’m partial to black and white, am still learning my typography, Ruby, and jQuery.

Name something that has inspired you recently?

I’ve been really enjoying finding the connections between a few really great books (Pragmatic Thinking and Learning, and Drive: The Surprising Truth About What Motivates Us to start). They’ve talked about how our traditional way of thinking and managing the process of “work” really doesn’t fall in line with what’s necessarily the most productive.

What do you prefer (and why)? Freelance work or full time employment?

I have the perfect job – working remotely for Intridea. I have all the stability and benefits of a full-time position, but with all the flexibility that you’d see from doing freelance work. Intridea is the high-school teacher who lets you have class outside.

What are your personal projects and goals for 2010?

I just wrote a blog post that got a fair bit of attention called So You Want To Be A Ruby Dev where I talk about the newcomer’s experience with the Ruby community and how with so many choices, it’s difficult to get started without one-on-one mentoring. I’m working on addressing this problem by being available as a mentor, and ensuring that we have updated and easy-to-find tutorials for newcomers.

In the meantime, we’re working hard to get the Rails Rumble 2010 competition ready for the October date. It’s a huge undertaking, but a great experience. I’m looking forward to seeing what teams come up with this year!

back to top
Posted 23 days ago at Railscasts

Here we finish up this upgrade series by removing all deprecation warnings and fixing some problems in the view.

back to top

Optitron: Easily add option and command parsing to your Ruby CLI:

We love command line interfaces. We’ve written before about how we use the Tumblr gem to post to this site. If you want to add a nice CLI to your Ruby app, Joshua Hull from the Padrino team has released Optitron, an easy way to support option and command parsing.

Install the gem

gem install optitron

A quick example

@parser = Optitron.new {
  opt 'verbose', "Be very loud"
  cmd "install", "This installs things" do
    arg "file", "The file to install"
  end
  cmd "show", "This shows things" do
    arg "first", "The first thing to show"
    arg "second", "The second optional thing to show", :required => false
  end
  cmd "kill", "This kills things" do
    opt "pids", "A list of pids to kill", :type => :array
    opt "pid", "A pid to kill", :type => :numeric
    opt "names", "Some sort of hash", :type => :hash
  end
  cmd "join", "This joins things" do
    arg "thing", "Stuff to join", :type => :greedy
  end
}

Then you can print those options with @parser.help:

Commands

show [first]           # This shows things
install [file]                 # This installs things
kill                           # This kills things
  -p/--pids=[ARRAY]            # A list of pids to kill
  -P/--pid=[NUMERIC]           # A pid to kill
  -n/--names=[HASH]            # Some sort of hash
join [thing1 thing2 ...]       # This joins things

Global options

-v/--verbose                   # Be very loud

Let’s see how Optitron parses inbound arguments

response = @parser.parse(%w(-v install file))
response.command
=> "install"
response.args
=> ["file"]
response.params
=> {"verbose" => true}

With four patch releases today, this gem is moving fast but one to keep an eye on.

[Source on GitHub]

back to top

Nitrode: A lightweight HTTP Server on top of Node.js:

Released earlier today was Nitrode, which aims to be FASTCGI type server for Node.js, this is a server for those who want the power of something like Nginx, but would prefer to write the logic in JavaScript.

Nitrode boasts pretty impressive features for a first release, some notable features including:

  • Virtual Host Configuration
  • Redirection
  • ETags and If-Modified-Since support
  • Static file serving
  • SSL support
  • HTTP Basic Authentication

For now, there’s an example.js file up in the repository on github, and it’s author, Oliver Morgan still says there’s a lot of work to be done on it.

[Source on GitHub] [Release notes]

back to top

mongomatic: Minimal Ruby mapper for Mongo:

If you’re a close-to-the-metal sort of developer who eschews conveniences like relationships, indexes, and query APIs, then check out Mongomatic from Ben Myles. Mongomatic aims to do ‘just enough’ by mapping your models to MongoDB collections but leaves the rest to you:

  • No additional query API. You simply drop down to the Ruby driver.
  • No relationships. Simply write your own finder methods.
  • No validations. Unless you write your own.

What’s the upside you may ask? Minimal dependencies and better alignment with MongoDB native conventions.

A sample model

require 'mongomatic'

class User < Mongomatic::Base
  def validate
    self.errors << ["Name", "can't be empty"]  if self["name"].blank?
    self.errors << ["Email", "can't be empty"] if self["email"].blank?
  end
end

# set the db for all models:
Mongomatic.db = Mongo::Connection.new.db("mongomatic_test")
# or you can set it for a specific model:
User.db = Mongo::Connection.new.db("mongomatic_test_user")

Find a single user:

found = User.find_one({"name" => "Ben Myles"})
=> #BSON::ObjectID('4c32834f0218236321000001'), "name"=>"Ben Myles", "email"=>"me@somewhere.com"}, @removed=false, @is_new=false, @errors=[]>

Iterate over a cursor, the MongoDB way:

cursor = User.find({"name" => "Ben Myles"})
=> #"Ben Myles"}>>
found = cursor.next
=> #BSON::ObjectID('4c32834f0218236321000001'), "name"=>"Ben Myles", "email"=>"me@somewhere.com"}, @removed=false, @is_new=false, @errors=[]>
found.remove
=> 67
User.count
=> 0
User.find({"name" => "Ben Myles"}).next
=> nil

If you need a quick-and-dirty model for your MongoDB Ruby app, give Mongomatic a look. It looks like a lightweight alternative to MongoMapper and Mongoid.

[Source on GitHub] [Homepage]

back to top
Favorite
Posted 25 days ago at Katz Got Your Tongue?

For a while now, the Ruby community has become enamored in the latest new hotness, evented programming and Node.js. It’s gone so far that I’ve heard a number of prominent Rubyists saying that JavaScript and Node.js are the only sane way to handle a number of concurrent users.

I should start by saying that I personally love writing evented JavaScript in the browser, and have been giving talks (for years) about using evented JavaScript to sanely organize client-side code. I think that for the browser environment, events are where it’s at. Further, I don’t have any major problem with Node.js or other ways of writing server-side evented code. For instance, if I needed to write a chat server, I would almost certainly write it using Node.js or EventMachine.

However, I’m pretty tired of hearing that threads (and especially Ruby threads) are completely useless, and if you don’t use evented code, you may as well be using a single process per concurrent user. To be fair, this has somewhat been the party line of the Rails team years ago, but Rails has been threadsafe since Rails 2.2, and Rails users have been taking advantage of it for some time.

Before I start, I should be clear that this post is talking about requests that spent a non-tiny amount of their time utilizing the CPU (normal web requests), even if they do spend a fair amount of time in blocking operations (disk IO, database). I am decidedly not talking about situations, like chat servers where requests sit idle for huge amounts of time with tiny amounts of intermittent CPU usage.

Threads and IO Blocking

I’ve heard a common misperception that Ruby inherently “blocks” when doing disk IO or making database queries. In reality, Ruby switches to another thread whenever it needs to block for IO. In other words, if a thread needs to wait, but isn’t using any CPU, Ruby’s built-in methods allow another waiting thread to use the CPU while the original thread waits.

If every one of your web requests uses the CPU for 30% of the time, and waits for IO for the rest of the time, you should be able to serve three requests in parallel, coming close to maxing out your CPU.

Here’s a couple of diagrams. The first shows how people imagine requests work in Ruby, even in threadsafe mode. The second is how an optimal Ruby environment will actually operate. This example is extremely simplified, showing only a few parts of the request, and assuming equal time spent in areas that are not necessarily equal.


Untitled.001.png


Untitled.002.png


I should be clear that Ruby 1.8 spends too much time context-switching between its green threads. However, if you’re not switching between threads extremely often, even Ruby 1.8′s overhead will amount to a small fraction of the total time needed to serve a requests. A lot of the threading benchmarks you’ll see are testing pathological cases involve huge amounts of threads, not very similar to the profile of a web server.

(if you’re thinking that there are caveats to my “optimal Ruby environment”, keep reading)

“Threads are just HARD”

Another common gripe that pushes people to evented programming is that working with threads is just too hard. Working hard to avoid sharing state and using locks where necessary is just too tricky for the average web developer, the argument goes.

I agree with this argument in the general case. Web development, on the other hand, has an extremely clean concurrency primitive: the request. In a threadsafe Rails application, the framework manages threads and uses an environment hash (one per request) to store state. When you work inside a Rails controller, you’re working inside an object that is inherently unshared. When you instantiate a new instance of an ActiveRecord model inside the controller, it is rooted to that controller, and is therefore not used between live threads.

It is, of course, possible to use global state, but the vast majority of normal, day-to-day Rails programming (and for that matter, programming in any web framework in any language with a request model) is inherently threadsafe. This means that Ruby will transparently handle switching back and forth between active requests when you do something blocking (file, database, or memcache access, for instance), and you don’t need to personally manage the problems the arise when doing concurrent programming.

This is significantly less true about applications, like chat servers, that keep open a huge number of requests. In those cases, a lot of the application logic happens outside the individual request, so you need to personally manage shared state.

Historical Ruby Issues

What I’ve been talking about so far is how stock Ruby ought to operate. Unfortunately, a group of things have historically conspired to make Ruby’s concurrency story look much worse than it actually ought to be.

Most obviously, early versions of Rails were not threadsafe. As a result, all Rails users were operating with a mutex around the entire request, forcing Rails to behave like the first “Imagined” diagram above. Annoyingly, Mongrel, the most common Ruby web server for a few years, hardcoded this mutex into its Rails handler. As a result, if you spun up Rails in “threadsafe” mode a year ago using Mongrel, you would have gotten exactly zero concurrency. Also, even in threadsafe mode (when not using the built-in Rails support) Mongrel spins up a new thread for every request, not exactly optimal.

Second, the most common database driver, mysql is a very poorly behaved C extension. While built-in I/O (file or pipe access) correctly alerts Ruby to switch to another thread when it hits a blocking region, other C extensions don’t always do so. For safety, Ruby does not allow a context switch while in C code unless the C code explicitly tells the VM that it’s ok to do so.

All of the Data Objects drivers, which we built for DataMapper, correctly cause a context switch when entering a blocking area of their C code. The mysqlplus gem, released in March 2009, was designed to be a drop-in replacement for the mysql gem, but fix this problem. The new mysql2 gem, written by Brian Lopez, is a drop-in replacement for the old gem, also correctly handles encodings in Ruby 1.9, and is the new default MySQL driver in Rails.

Because Rails shipped with the (broken) mysql gem by default, even people running on working web servers (i.e. not mongrel) in threadsafe mode would have seen a large amount of their potential concurrency eaten away because their database driver wasn’t alerting Ruby that concurrent operation was possible. With mysql2 as the default, people should see real gains on threadsafe Rails applications.

A lot of people talk about the GIL (global interpreter lock) in Ruby 1.9 as a death knell for concurrency. For the uninitiated, the GIL disallows multiple CPU cores from running Ruby code simultaneously. That does mean that you’ll need one Ruby process (or thereabouts) per CPU core, but it also means that if your multithreaded code is running correctly, you should need only one process per CPU core. I’ve heard tales of six or more processes per core. Since it’s possible to fully utilize a CPU with a single process (even in Ruby 1.8), these applications could get a 4-6x improvement in RAM usage (depending on context-switching overhead) by switching to threadsafe mode and using modern drivers for blocking operations.

JRuby, Ruby 1.9 and Rubinius, and the Future

Finally, JRuby already runs without a global interpreter lock, allowing your code to run in true parallel, and to fully utilize all available CPUs with a single JRuby process. A future version of Rubinius will likely ship without a GIL, also opening the door to utilizing all CPUs with a single Ruby process.

And all modern Ruby VMs that run Rails (Ruby 1.9′s YARV, Rubinius, and JRuby) use native threads, eliminating the annoying tax that you need to pay for using threads in Ruby 1.8. Again, though, since that tax is small relative to the time for your requests, you’d likely see a non-trivial improvement in latency in applications that spend time in the database layer.

To be honest, a big part of the reason for the poor practical concurrency story in Ruby has been that the Rails project didn’t take it seriously, which it difficult to get traction for efforts to fix a part of the problem (like the mysql driver). We took concurrency very seriously in the Merb project, leading to the development of proper database drivers for DataMapper (Merb’s ORM), and a top-to-bottom understanding of parts of the stack that could run in parallel (even on Ruby 1.8), but which weren’t. Rails 3 doesn’t bring anything new to the threadsafety of Rails itself (Rails 2.3 was threadsafe too), but by making the mysql2 driver the default, we have eliminated a large barrier to Rails applications performing well in threadsafe mode without any additional research.

back to top
Posted 25 days ago at Ruby Inside

http://mongomatic.com/ (or on Ruby Inside)

Back in June, I did a comparison of Mongoid and MongoMapper, the two best known MongoDB libraries for Ruby. Now, Ben Myles has brought another to the fore: Mongomatic.

Mongomatic is a Ruby library that lets you easily model your MongoDB documents in your applications.

The primary design goals of Mongomatic are simplicity and adherence to MongoDB conventions. Mongomatic is not an ActiveRecord clone and has been designed to fit nicely with the document-oriented nature of MongoDB.

Features include cursors, hash access to your document and embedded documents, validations, callbacks and conventions for creating indexes and relationships.

Ben Myles

I haven't given it a try myself yet, but Ben's done a good job of presenting it, along with example code, so check it out if MongoDB is your bag.

If you want more MongoDB related news, check out coder.io's #mongodb tag. Lots of great stuff there.

back to top
Posted 25 days ago at Ruby Inside

SunnyConf is a single-track, one day conference taking place Sept. 25th in sunny Phoenix, AZ. There will be 8 speakers and a keynote, as well as lightning talks. Speakers include:

Check out the official SunnyConf Web site to see other speakers and keep up to date on the conference. Tickets are priced at $100. A limited number of seats are available, so get your tickets now!

If you missed out on RubyConf, which sold out just a few days ago, this could make for a good tonic.

back to top
Posted 25 days ago at The GitHub Blog

I'm currently at the FOSSLC conference in Ottawa, CA and we're going out to Dantessa Italian Bar tonight starting at 21:00 (9pm for us Americans). GitHub will be buying a round or two, so come meet the FOSSLC attendees who will be newly imbued with amazing tech knowledge and share some beer with us.


View Larger Map

Hope to see you there!

Details: Dantessa Italian Bar
131 Cooper Street Ottawa, Ontario
9:00pm (21:00)

Punch the guy wearing the short sleeved collared brown shirt if you're having a hard time getting a free beer

back to top

facebook-ios-sdk: Drop Facebook into your iOS application:

Facebook loves iOS developers. First, they gave us Three20, a nice iOS app framework extracted from their popular native app. Now they’ve released the Facebook iOS SDK which lets you easily add authorization, API calls, and Facebook dialogs to your iOS apps.

Authorization

To authorize a user using OAuth2 you can simply create the Facebook client and call authorize

facebook = [[Facebook alloc] init];
[facebook authorize:apiKey permissions:permissions delegate:self];

Making API calls

Now you can do things like getting info for the authenticating user:

[facebook requestWithGraphPath:@"me" andDelegate:self];

or get that users’s friends

[facebook requestWithGraphPath:@"me/friends" andDelegate:self];

[Source on GitHub]

back to top

tweet-button: Easy Twitter Tweet Buttons for your Rails apps:

Nobody does 0day gems like Intridea. First they released OAuth2 the same day Facebook announced their plans for it. This week, they created tweet-button the same day Twitter unveiled their new official tweet button.

Tweet button is a simple helper to provide a nice Ruby interface for adding the button to your page:

= tweet_button :via => "changelogshow", :url => "http://wynn.fm/twbtns", :text => "This is so meta!"

which will yield

Configurable options include:

  • :url - The URL to share; the default is the current URL.
  • :text - The text that will appear in the tweet; the default is “Check this out!”
  • :via - The attribution. Defaults to “tweetbutton”, but you should change that.
  • :lang - Set the language for the tweet (no default).
  • :related - Related Twitter accounts (no default).
  • :count - The tweet count box position (values can be “none”, “horizontal”, or “vertical”; default is “vertical”).

Check the README for advanced features.

[Source on GitHub]

back to top

fikus: Cloud-friendly Ruby CMS powered by Padrino and MongoDB:

For the developer, a blog or CMS is like a favorite t-shirt. It doesn’t have to be fashionable, but it’s got to fit. It’s in that spirit that we highlight Fikus, the new simple Ruby CMS from Tim Gourley.

What makes Fikus special?

  • Powered by Padrino. Sinatra’s cool Italian cousin provides a built-in admin panel. Checkout out Episode 0.2.7 for more on this cool Ruby web framework.
  • MongoDB. Document-oriented databases are great CMS databases, as we discussed in Episode 0.0.7
  • HAML-based layouts. Never hunt down a closing
again.
  • Cloud friendly. Fikus is ready for Engine Yard AppCloud and Heroku out of the box.
  • Fikus is also chock full of caching optimizations and Rack middleware, or go add your own.

    [Source on GitHub]

    back to top
    Posted 25 days ago at The GitHub Blog

    Earlier today we rolled out a minor design update to the site. Notably, we have a brand new home page (remember, you can always get to the homepage at http://github.com/home):

    It's simpler, sweeter and to the point. GitHub has evolved a lot since launch – and we've been bad at explaining that to newbies. Hopefully this is the first step of many to better explain our offerings.

    You'll also notice a new footer and language switcher:

    Did you know we also offer Training?

    For the astute, you'll notice lots of CSS improvments (only down to one image-based gradient!).

    Hope you all enjoy!

    back to top
    Favorite
    Posted 26 days ago at Ruby5

    Railtie, Unencumbered, You're Cuking it Wrong, whereuat, rake.vim, and Gem in a Box.

    Listen to this episode on Ruby5

    This episode is sponsored by NewRelic RPM
    Did you know that New Relic Has deployment tracking? All you do is modify your capistrano task to let new relic know when you do a deployment. Then when you view you stats on new relic after the deployment, you'll actually see a line on each of your new relic graphs so you'll be able to see how performance was affected. Check out the video over on NewRelic.com to learn more.

    Railtie
    Create Rails 3 plugins easily using Railtie.

    Unencumbered Updated for RSpec 2
    Hashrocket's "you got Cucumber in my RSpec" gem is now RSpec 2 compatible. Use Given-When-Then in your integration specs to get something that looks like Ruby plus Cucumber.

    You're Cuking It Wrong
    We interview CJ Kihlbom from eLabs about Jonas Niklas's blog post. In a nutshell, the problem isn't Cucumber, it's you. ;)

    whereuat
    Adds a slide-out sidebar to your Rails app that directs your stakeholders to test stories marked as "delivered" in Pivotal Tracker.

    vim.rake
    With rake.vim, you can use all those parts of rails.vim that you wish you could use on your other Ruby projects on anything with a Rakefile, including :R and :A, :Rlib and friends, and of course :Rake. It's great when paired with gem open and bundle open.

    Gem in a Box
    A small Sinatra app for internal gem hosting.

    back to top