Ruby Inside 2025年03月14日T07:06:55Z http://www.rubyinside.com/feed/atom WordPress Peter Cooper http://twitter.com/peterc <![cdata[raptor: A Forthcoming Ruby Web Server for Faster App Deployment]]> http://www.rubyinside.com/?p=6168 2014年10月21日T13:20:59Z 2014年10月21日T13:20:59Z

Raptor bills itself as a new Ruby "app server" and it claims to blow everything else out of the water performance-wise (by between 2-4x!) whether that’s Unicorn, Puma, Passenger, or even TorqueBox on JRuby. The bad news for now is there’s no source or repo yet and only a handful of people (including me) have been given a sneak peek, although a public beta is promised on November 25th.

The history of Ruby webapp deployment

The deployment of Ruby (and therefore Rails) webapps was a painful mess for years, a state I lamented 7 years ago in No True ‘mod_ruby’ is Damaging Ruby’s Viability on the Web. Read More

]]>

Raptor bills itself as a new Ruby "app server" and it claims to blow everything else out of the water performance-wise (by between 2-4x!) whether that’s Unicorn, Puma, Passenger, or even TorqueBox on JRuby. The bad news for now is there’s no source or repo yet and only a handful of people (including me) have been given a sneak peek, although a public beta is promised on November 25th.

The history of Ruby webapp deployment

The deployment of Ruby (and therefore Rails) webapps was a painful mess for years, a state I lamented 7 years ago in No True ‘mod_ruby’ is Damaging Ruby’s Viability on the Web. Thankfully, shortly thereafter a number of projects came out to make life easier, the most famous being Phusion Passenger (then known as mod_rails) in April 2008.

Things have continued to improve gradually over the years, with Passenger getting consistently better, and new approaches such as those offered by Unicorn and Puma, using JRuby, as well as proxying through Nginx, coming into the picture.

Enter Raptor

Raptor, a new entry to the burgeoning world of Ruby Web servers, boasts some compelling features. "Visibility" is cited as a key feature so that you can look ‘into’ your app and analyze its performance as easily as possible using a JSON API (so building your own tools around the API should be simple). Raptor also uses the HTTP parser from Node which itself was derived from Nginx’s HTTP parser; both are renowned for their speed and stability. Raptor boasts a zero-copy, concurrent, evented architecture which makes it efficient memory and IO-wise - so even if you have slow clients or a slow network, these won’t bring your app server to a stuttering standstill.

Another feature that jumped out at me is integrated caching. Raptor doesn’t rely on an external services like memcached or Redis at all, but is truly internal and optimized specifically for Web workloads. If you’ve never set up caching before, this could provide a big boost as with Raptor it’ll be available "out of the box".

The initial results seem promising. Fabio Akita has already shared some early benchmark results which broadly mirror my own experience (disclaimer: as someone with rather little experience and authority in benchmarking, my benchmarks are oriented around Raptor’s own benchmarking suite) but, as always, YMMV and such benchmarks are often criticized.

The waiting game..

The team behind Raptor promise they’ll be releasing some interesting blog posts soon about the technology behind it, including how the cache is implemented and has been optimized, how the zero-copy system works and how it’ll benefit your code, and similar things. So keep an eye on rubyraptor.org, especially around November 25th.

]]>
0
Peter Cooper http://twitter.com/peterc <![cdata[ruby’s Unary Operators and How to Redefine Their Functionality]]> http://www.rubyinside.com/?p=5610 2014年10月16日T09:34:33Z 2014年10月16日T05:05:16Z In math, a unary operation is an operation with a single input. In Ruby, a unary operator is an operator which only takes a single 'argument' in the form of a receiver. For example, the - on -5 or ! on !true.

In contrast, a binary operator, such as in 2 + 3, deals with two arguments. Here, 2 and 3 (which become one receiver and one argument in a method call to +).

Ruby only has a handful of unary operators, and while it's common to redefine binary operators like + or [] to give your objects some added syntactic sugar, unary operators are less commonly redefined. Read More

]]>
In math, a unary operation is an operation with a single input. In Ruby, a unary operator is an operator which only takes a single 'argument' in the form of a receiver. For example, the - on -5 or ! on !true.

In contrast, a binary operator, such as in 2 + 3, deals with two arguments. Here, 2 and 3 (which become one receiver and one argument in a method call to +).

Ruby only has a handful of unary operators, and while it's common to redefine binary operators like + or [] to give your objects some added syntactic sugar, unary operators are less commonly redefined. In my experience, many Rubyists aren't aware that unary operators can be redefined and.. technically you can't "redefine an operator" but Ruby's operators frequently use specially named methods behind the scenes, and as you'll know.. redefining a method is easy in Ruby!

A Quick Example with -@

Let's ease into things with the - unary operator. The - unary operator is not the same thing as the - binary operator (where a binary operator has two operants). By default, the - unary operator is used as notation for a negative number, as in -25, whereas the - binary operator performs subtraction, as in 50 - 25. While they look similar, these are different concepts, different operators, and resolve to different methods in Ruby.

Using the - unary operator on a string in irb:

> -"this is a test"
NoMethodError: undefined method `-@' for "this is a test":String

The String class doesn't have unary - defined but irb gives us a clue on where to go. Due to the conflict between the unary and binary versions of -, the unary version's method has a suffix of @. This helps us come up with a solution:

str = "This is my STRING!"
def str.-@
 downcase
end
p str # => "This is my STRING!"
p -str # => "this is my string!"

We've defined the unary - operator by defining its associated -@ method to translate its receiving object to lower case.

Some Other Operators: +@, ~, ! (and not)

Let's try a larger example where we subclass String and add our own versions of several other easily overridden unary operators:

class MagicString < String def +@ upcase end def -@ downcase end def ! swapcase end def ~ # Do a ROT13 transformation - http://en.wikipedia.org/wiki/ROT13 tr 'A-Za-z', 'N-ZA-Mn-za-m' end end str = MagicString.new("This is my string!") p +str # => "THIS IS MY STRING!"
p !str # => "tHIS IS MY STRING!"
p (not str) # => "tHIS IS MY STRING!"
p ~str # => "Guvf vf zl fgevat!"
p +~str # => "GUVF VF ZL FGEVAT!"
p !(~str) # => "gUVF VF ZL FGEVAT!"

This time we've not only redefined -/-@, but the + unary operator (using the +@ method), ! and not (using the ! method), and ~.

I'm not going to explain the example in full because it's as simple as I could get it while still being more illustrative than reams of text. Note what operation each unary operator is performing and see how that relates to what is called and what results in the output.

Special Cases: & and *

& and * are also unary operators in Ruby, but they're special cases, bordering on 'mysterious syntax magic.' What do they do?

& and to_proc

Reg Braithwaite's The unary ampersand in Ruby post gives a great explanation of &, but in short & can turn objects into procs/blocks by calling the to_proc method upon the object. For example:

p ['hello', 'world'].map(&:reverse) # => ["olleh", "dlrow"]

Enumerable#map usually takes a block instead of an argument, but & calls Symbol#to_proc and generates a special proc object for the reverse method. This proc becomes the block for the map and thereby reverses the strings in the array.

You could, therefore, 'override' the & unary operator (not to be confused by the equivalent binary operator!) by defining to_proc on an object, with the only restriction being that you must return a Proc object for things to behave. You'll see an example of this later on.

* and splatting

There's a lot of magic to splatting but in short, * can be considered to be a unary operator that will 'explode' an array or an object that implements to_a and returns an array.

To override the unary * (and not the binary * - as in 20 * 32), then, you can define a to_a method and return an array. The array you return, however, will face further consequences thanks to *'s typical behavior!

A Full Example

We've reached the end of our quick tour through Ruby's unary operators, so I wanted to provide an example that shows how to override (or partially override) them that should stand as its own documentation:

class MagicString < String
 def +@
 upcase
 end
 def -@
 downcase
 end
 def ~
 # Do a ROT13 transformation - http://en.wikipedia.org/wiki/ROT13
 tr 'A-Za-z', 'N-ZA-Mn-za-m'
 end
 def to_proc
 Proc.new { self }
 end
 def to_a
 [self.reverse]
 end
 def !
 swapcase
 end
end
str = MagicString.new("This is my string!")
p +str # => "THIS IS MY STRING!"
p ~str # => "Guvf vf zl fgevat!"
p +~str # => "GUVF VF ZL FGEVAT!"
p %w{a b}.map &str # => ["This is my string!", "This is my string!"]
p *str # => "!gnirts ym si sihT"
p !str # => "tHIS IS MY STRING!"
p (not str) # => "tHIS IS MY STRING!"
p !(~str) # => "gUVF VF ZL FGEVAT!"

It's almost a cheat sheet of unary operators :-)

A Further Example: The TestRocket

TestRocket is a tiny testing library I built for fun a few years ago. It leans heavily on unary operators. For example, you can write tests like this:

+-> { Die.new(2) }
--> { raise }
+-> { 2 + 2 == 4 }
# These two tests will deliberately fail
+-> { raise }
--> { true }
# A 'pending' test
~-> { "this is a pending test" }
# A description
!-> { "use this for descriptive output and to separate your test parts" }

The -> { } sections are just Ruby 1.9+ style 'stabby lambdas' but, with assistance from Christoph Grabo, I added unary methods to them so that you can prefix +, -, ~, or ! to get different behaviors.

Hopefully you can come up with some more useful application for unary methods on your own objects ;-)

]]>
1
Peter Cooper http://twitter.com/peterc <![cdata[this Month in Ruby: PeepCode Acquired, Rails 3.2.14, And More]]> http://www.rubyinside.com/?p=6156 2013年07月25日T20:16:48Z 2013年07月25日T16:25:44Z Welcome to a roundup of Ruby news, articles, videos, and more, for July 2013 cobbled together from my e-mail newsletter, Ruby Weekly.

Highlights include: PeepCode acquired by Pluralsight, Practicing Ruby archives made public, Rails 3.2.14, and an interesting interview with Matz.

Featured

The First Four Volumes of Practicing Ruby, Now Available Online Practicing Ruby is a high quality, paid Ruby journal run by Gregory Brown, but he's made archives of over 60 articles available to the public. There's a ton of stuff to enjoy here.

PeepCode Acquired by Pluralsight Ruby and Rails screencasting pioneer Geoffrey Grosenbach has announced he has sold Peepcode to Pluralsight, a large online training provider. Read More

]]>
Welcome to a roundup of Ruby news, articles, videos, and more, for July 2013 cobbled together from my e-mail newsletter, Ruby Weekly.

Highlights include: PeepCode acquired by Pluralsight, Practicing Ruby archives made public, Rails 3.2.14, and an interesting interview with Matz.

Featured

The First Four Volumes of Practicing Ruby, Now Available Online
Practicing Ruby is a high quality, paid Ruby journal run by Gregory Brown, but he's made archives of over 60 articles available to the public. There's a ton of stuff to enjoy here.

PeepCode Acquired by Pluralsight
Ruby and Rails screencasting pioneer Geoffrey Grosenbach has announced he has sold Peepcode to Pluralsight, a large online training provider.

The Plan for RSpec 3
RSpec 2.0 was released in October 2010 and RSpec 2.14 will be the last RSpec 2 feature release. Work on RSpec 3 has begun and Myron Marston shares what's going to be involved.

Rails 3.2.14 RC1 and RC2 Released
A variety of bug fixes for Rails 3.2 arrived in 3.2.14 RC1 with one minor regression fixed in RC2. Final due soon.

The Future of Computing - An Interview with Matz
Last year, Ruby's creator Yukihiro 'Matz' Matsumoto released a book called The Future of Computing (only in Japanese, I believe) and did an interview with a Chinese publisher. Fred Wu has translated it into English.

RSpec 2.14 Released
Myron Marston unveils the last 2.x feature release of the popular spec framework and announces work is well underway for the future RSpec 3. 2.14 includes a new feature called 'spies' which is shown off here.

Functional Programming and Ruby
At GoRuCo 2013, Pat Shaughnessy gave a 40 minute talk comparing Haskell (a functional language) to Ruby and looked at how to implement common functional patterns in Ruby. Well explained and backed by good slides.

Reading

Streaming with Rails 4
Saurabh Bhatia looks at Rails 4's support for live streaming (the ability to send partial requests out to the client on the fly).

Reading the Ruby Source to Understand Rails Idiosyncrasies
I'm not sure you always need to dig quite so deep but Eno Compton takes an interesting journey through MRI's source code to see the difference between Range#cover? and Range#include?

Speed Up Heroku Deploys
Alex MacCaw was suffering from slow deploys to Heroku but he found a workaround.

Shoes 4 – A Progress Report
Shoes was a graphical toolkit put together by Why the Lucky Stiff that made it simple to create GUI apps in Ruby. Since Why disappeared, others have picked up work on it, and Shoes 4 is set to be a complete rewrite.

Put Yourself on Rails with A Push of A Button
A technique for quickly bringing up a workspace for doing Rails work (including terminals, a Rails console, a Rails server, etc.)

Multitenancy with Rails: An E-book by Ryan Bigg
Ryan Bigg, of Rails in Action fame, is writing an e-book about building a multi-tenanted Rails app.

Incremental Redesign with Rails
Lars Klevan shows how to use prepend_view_path to make in-progress redesigns on a production codebase simpler.

How to Declutter Your 'lib' Directory
If you have an established Rails project, its 'lib' folder might be getting a little full. Kuba Suder looks at ways to clean it up and put things elsewhere.

Design Patterns: The Template Method Pattern
An introductory Ruby-oriented look at arguably the simplest design pattern.

Object Oriented Rails: Writing Better Controllers
Damien Le Berrigaud of Pivotal Labs tries to avoid stubs and mocks and leans on dependency injection to test his controllers' code.

Vimscript And You
HashRocket's Jonathan Jackson demonstrates how you can use RSpec against Vim to aid in the development of a Vim plugin with Vimscript.

MotionPhrase: Next Level Localization for RubyMotion Applications
PhraseApp is a translation management tool for producing multilingual Web sites, Rails apps, etc, but it also works for localizing RubyMotion apps too, as demonstrated here.

Ruby's Eigenclasses Demystified
Andrea Singh looks at Ruby's quirky 'eigenclasses' (a.k.a. metaclasses) and explains things in both code and diagrams. Dates from 2011 but worth revisiting.

The Self-Pipe Trick Explained
Jesse Storimer shows off a cute Unix trick/technique in Ruby.

Practical RSpec Wrapping
Why would you want to use around hooks in RSpec? Dru Riley explains.

Using PostgreSQL's 'hstore' in A Rails Application on Engine Yard Cloud
If you want to take advantage of schemaless features without abandoning your relational database, using 'hstore' within Postgres is a great option. Here's an introduction on using the hstore PostgreSQL extension in a Rails app.

Implementing Subdomain and Custom Domain Support in Rails
A look at how one development team implement subdomain and custom domain features in their Rails app.

Events

dotRB: The Largest Ruby Conference in France (October 18, Paris)
Following on from a successful 'dotJS' JavaScript event comes dotRB. Announced speakers so far include Steve Klabnik, Konstantin Haase, and Brian Ford.

Watching

11 Talks from La Conf Paris
Some big names to enjoy here including Yehuda Katz, Amy Hoy, Sandi Metz, and Steve Klabnik.

Deathmatch: Bundler vs Rubygems.org
At GoRuCo 2013, Andre Arko told the story of the quest to make 'bundle install' faster.

How to Set Up RSpec
A well produced 6 minute screencast.

To Know A Garbage Collector
Mike Bernstein discusses his experiments with MRI Ruby's garbage collector, his investigations into other languages and the influence of their GC implementations, the history of the subject, and more.

Kata and Analysis with Jim Weirich
From RubyConf India 2013 comes a live coding session by the inimitable Jim Weirich where he walks through the popular 'roman numeral' conversion kata using TDD along the way.

Aaron 'tenderlove' Patterson's RubyConf India 2013 Keynote
An hour with Ruby and Rails core contributor Aaron 'tenderlove' Patterson covering esoteric Ruby stuff and Postgres to career advice and cats. Warning: The audio is rather poor here and cuts out entirely for the second half so don't waste your time if this will drive you crazy.

5 Minutes of EuRuKo 2013
European Ruby conference (EuRuKo) took place in Athens last month and Clemens Helm has put together a 5 minute collection of clips and insights from the event. Includes Matz, Xavier Noria, Benjamin Smith, Pat Shaughnessy and Steve Klabnik.

Nokogiri: History and Future
Nokogiri is the most popular way to parse and process XML in Ruby and at GoRuCo 2013, Mike Dalessio gave a short 11 minute talk on the origins of the project, how to determine if it suits you, and looks at some of the tooling around it.

Libraries, Code and Tools

Upton: A Web Scraping Framework
A Ruby-based web-scraping framework that abstracts away the common parts of web scraping so developers can concentrate on the unique parts of their project.

LanguageFilter: Detect and Optionally Filter Multiple Categories of Language
Wave goodbye to sex, hatred, profanity, violence, etc, in your app.

Lita: A Ruby Chat Bot with Redis-based Storage
Can be twisted to work with any chat service and extended with plugins.

Pkgr: Make A Debian Package Out of A Rails App in 5 Minutes
A high-level tool that turns Rails applications into native Debian packages.

Flynn - Open Source Platform As A Service, Powered by Docker
Flynn is an as-yet-unreleased Heroku-inspired system to simplify deploying and maintaining apps. Instead of using complex config management systems, Flynn allows self-serve management of containerized deployments. The creator is currently trying to raise money to work on the project.

Jobs

Software Craftsperson at Bendyworks
If you're the type of person who learns new languages as a matter of course, contributes to open source for fun, and ships code with a calm and collected professionalism: you seem like our kind of developer. Join our world-class team in Madison, Wisconsin.

Senior backend- / API-developer at Rabble (Stockholm, Sweden)
Tired of bullshit ads? Help us develop Sweden's leading app for mobile offers, where customers and businesses meet on equal terms! Join us in the heart of Stockholm to play with geospatial data and Ruby API's all day long!

Ruby on Rails developer at SupaDupa (London, UK)
We're looking for an experienced Ruby on Rails developer to join the small team behind SupaDupa.me, an e-commerce platform aimed at creatives. Excited about the challenge of working on the full stack, from front-end dev to system administration? Get in touch!

Ruby Programmer: IT and System Automation
Want to change the future of education? We are trying to build an awesome team that enjoys challenges and results. Interested? Come work with us in beautiful Switzerland.

Ruby Developers at HouseTrip (London, UK)
Want to work with a 18-person team of passionate Ruby developers who love good code and care for their product in central London? We are currently hiring. Ranked by Wired Magazine the number two start-up in London (2012), HouseTrip is Europe’s largest holiday rental booking website!

Last but not least..

ruby -run -e httpd . -p5000
Run a local HTTP server with a single line of Ruby. Just one character longer than the classic python -m SimpleHTTPServer but more obviously flexible (plus, it's Ruby ;-)).

]]>
0
Jesse Storimer <![cdata[does the GIL Make Your Ruby Code Thread-Safe?]]> http://www.rubyinside.com/?p=6051 2013年06月29日T17:16:29Z 2013年06月19日T14:19:34Z This is a guest post by Jesse Storimer. He teaches the Unix fu workshop, an online class for Ruby developers looking to do some awesome systems hacking in Ruby and boost their confidence when it comes to their server stack. Spots are limited, so check it out the class while there's still room. He's also the esteemed author of Working with Unix Processes, Working with TCP Sockets and Working with Ruby Threads.

There are some misconceptions in the Ruby community about this question surrounding MRI's GIL. If you only take one thing away from this article today, let it be this: The GIL does not make your Ruby code thread-safe. Read More

]]>
This is a guest post by Jesse Storimer. He teaches the Unix fu workshop, an online class for Ruby developers looking to do some awesome systems hacking in Ruby and boost their confidence when it comes to their server stack. Spots are limited, so check it out the class while there's still room. He's also the esteemed author of Working with Unix Processes, Working with TCP Sockets and Working with Ruby Threads.

There are some misconceptions in the Ruby community about this question surrounding MRI's GIL. If you only take one thing away from this article today, let it be this: The GIL does not make your Ruby code thread-safe.

But you shouldn't take my word for it.

This series started off just trying to understand what the GIL is at a technical level. Part 1 explained how race conditions could occur in the C code that's used to implement MRI. Yet, the GIL seemed to eliminate that risk, at least for the Array#<< method we looked at.

Part 2 confirmed that the GIL did, in fact, make MRI's native C method implementations atomic. In other words, these native implementations were free from race conditions. These guarantees only applied to MRI's native C functions, not to the Ruby that your write. So we were left with a lingering question:

Does the GIL provide any guarantee that your Ruby code will be thread-safe?

I've already answered that question. Now I want to make sure that the misconception doesn't go any further.

Race conditions redux

Race conditions exist when some piece of data is shared between multiple threads, and those threads attempt to act on that data at the same time. When this happens without some kind of synchronization, like locking, your program can start to do unexpected things and data can be lost.

Let's step back and recap how such a race condition can occur. We'll use the following Ruby code example for this section:

class Sheep
 def initialize
 @shorn = false
 end
 def shorn?
 @shorn
 end
 def shear!
 puts "shearing..."
 @shorn = true
 end
end

This class definition should be nothing new. A Sheep is not shorn when initialized. The shear! method performs the shearing and marks the sheep as shorn.

sheep = Sheep.new
5.times.map do
 Thread.new do
 unless sheep.shorn?
 sheep.shear!
 end
 end
end.each(&:join)

The bit of code creates a new sheep and spawns 5 threads. Each thread races to check if the sheep has been shorn? If not, it invokes the shear! method.

Here's the result I see from running this on MRI 2.0 several times.

$ ruby check_then_set.rb
shearing...
$ ruby check_then_set.rb
shearing...
shearing...
$ ruby check_then_set.rb
shearing...
shearing...

Sometimes the same sheep is being shorn twice!

If you were under the impression that the GIL made your code 'just work' in the presence of multiple threads, this should dispel that. The GIL can make no such guarantee. Notice that the first time running the file, the expected result was produced. In subsequent runs, unexpected output was produced. If you continued running the example, you'll see still different variations.

These unexpected results are due to a race condition in your Ruby code. It's actually a common enough race condition that there's a name to describe this pattern: a check-then-set race condition. In a check-then-set race condition, two or more threads check a value, then set some state based on that value. With nothing to provide atomicity, it's possible that two threads race past the 'check' phase, then both perform the 'set' phase.

Recognizing race conditions

Before we look at how to fix this, first I want you to understand how to recognize this. I owe @brixen for introducing to me the terminology of interleavings in the context of concurrency. It's really helpful.

Remember that a context switch can occur on any line of your code. When switching from one thread to another, imagine your program being chopped up into a set of discrete blocks. This sequential set of blocks is a set of interleavings.

At one end of the spectrum, it's possible that there's a context switch after every line of code! This set of interleavings would have each line of code interleaved. At the other end of the spectrum, it's possible that there are no context switches during the body of the thread. This set of interleavings would have all the code in its original order for each thread. In between these two ends, there are lots of ways that your program can be chopped up and interleaved.

Some of these interleavings are OK. Not every line of code introduces a race condition. But imagining your programs as a set of possible interleavings can help you recognize when race conditions do occur. I'll use a series of diagrams to show this code may be interleaved by two Ruby threads.

Just to make the diagrams simpler, I replaced the shear! method call with the code from the body of the method.

Consider this diagram the legend for the ones to follow; the code highlighted in red is the set of interleavings from Thread A, the code highlighted in blue is the set of interleavings from Thread B.

Now let's see how this code could be interleaved by simulating context switches. The simplest case is if neither thread is interrupted during the course of executing this code. This would result in no race conditions and would produce the expected output for us. That might look like this:

Now I've organized the diagram so you can see the sequential ordering of events. Remember that the GIL locks around the execution of Ruby code, so two threads can't truly run in parallel. The ordering of events here is sequential, starting at the top and working down.

In this interleaving, Thread A did all of its work, then the thread scheduler triggered a context switch to Thread B. Since Thread A had already done the shearing and updated the shorn variable, Thread B didn't have anything to do.

But it isn't always this simple. Remember that the thread scheduler could trigger a context switch at any point in this block of code. This time we just got lucky.

Let's look at a more nefarious example, one that would produce unexpected output for us.

In this possible interleaving, the context switch occurs right at a point that can cause trouble. Thread A checks the condition and starts shearing. Then the thread scheduler schedules a context switch and Thread B takes over. Even though Thread A already performed the shearing, it didn't get a chance to update the shorn attribute yet, so Thread B doesn't know about it.

Thread B checks the condition for itself, finds it to be false, and shears the sheep again. Once it finishes, Thread A is scheduled again and finishes execution. Even though Thread B set shorn = true when it ran through the code, Thread A does it again because it picks up exactly where it left off.

A sheep getting shorn twice may not seem like much to care about, but replace sheep with invoice, and shearing with collecting payment; we would have some unhappy customers!

I'll share one more example to illustrate the non-deterministic nature of things here.

This just adds more context switches, so each thread progresses a little bit at a time, but keeps switching back and forth. Let your mind take this to its logical conclusion, it's possible for a context switch to happen on any line of the program. The interleaving that occurs can also be different each time the code is executed, so it may produce the expected result on one iteration, and an unexpected result the next time around.

This is really a great way to think about race conditions. When you're writing multi-threaded code, you want to be thinking about how the program might be chopped up and interleaved, and the effects of various interleavings. If it seems that some interleavings will lead to incorrect results, you should re-think your approach to the problem or introduce synchronization with Mutex.

This is terrible!

At this point it seems fitting to tell you that you can make this code example thread-safe by introducing synchronization with Mutex. It's true, you can do that. But I intentionally cooked up this example to prove a point; it's terrible code. You shouldn't write code like this in a multi-threaded environment.

Whenever you have multiple threads sharing a reference to an object, and making modifications to it, you're going to run into trouble unless you have some kind of locking in place to prevent a context switch from happening in the middle of the modification.

However, this particular race condition is easily solvable without explicitly using locks in your code. Here's one solution using Queue:

require 'thread'
class Sheep
 # ...
end
sheep = Sheep.new
sheep_queue = Queue.new
sheep_queue << sheep
5.times.map do
 Thread.new do
 begin
 sheep = sheep_queue.pop(true)
 sheep.shear!
 rescue ThreadError
 # raised by Queue#pop in the threads
 # that don't pop the sheep
 end
 end
end.each(&:join)

I left out the Sheep implementation because it's the same. Now, instead of each thread sharing the sheep object and racing to shear it, the Queue provides the synchronization.

If you run this against MRI, or any of the other truly parallel Ruby implementations, it will produce the expected result every time. We've eliminated the race condition in this code. Even though all the threads may call the Queue#pop method at more-or-less the same time, it uses a Mutex internally to ensure that only one thread can receive the sheep.

Once this single thread receives the sheep, the race condition disappears. With just one thread, there's no one else to race with!

The reason I suggest using Queue instead of a lock is that its simpler to use a Queue correctly. Locks are notoriously easy to get wrong. They bring new concerns like deadlocking and performance degradations when used incorrectly. Using a data structure is like depending on an abstraction. It wraps up the tricky stuff in a more restrictive, but simpler API.

Lazy initialization

I'll just quickly point out that lazy initialization is another form of the the check-then-set race condition. The ||= operator effectively expands to

@logger ||= Logger.new
# expands to 
if @logger == nil
 @logger = Logger.new
end
@logger

Look at the expanded version and imagine where the interleavings could occur. With multiple threads and no synchronization, it's definitely possible for that @logger to be initialized twice. Again, initializing a Logger twice may not be a problem in this case, but I have seen bugs like this in the wild that do cause issues.

Reflections

I want to leave you with some lessons at the end of all this.

4 out of 5 dentists agree that multi-threaded programming is hard to get right.

At the end of the day, all that the GIL guarantees is that MRI's native C implementations of Ruby methods will be executed atomically (but even this has caveats). This behaviour can sometimes help us as Ruby developers, but the GIL is really there for the protection of MRI internals, not as a dependable API for Ruby developers.

So the GIL doesn't 'solve' thread-safety issues. As I said, getting multi-threaded programming right is hard, but we solve hard problems every day. One way that we work with hard problems is with good abstractions.

For example, when I need to do an HTTP request in my code, I need to use a socket. But I don't usually use a socket directly, that would be cumbersome and error-prone. Instead, I use an abstraction. An HTTP client provides a more restrictive, simpler API that hides the socket interactions and associated edge cases from me.

If multi-threaded programming is hard to get right, maybe you shouldn't be doing it directly.

"If you add a thread to your application, you've probably added five new bugs in doing so."

- Mike Perham

We're seeing more and more abstractions around threads. An approach that's catching on in the Ruby community is the Actor model of concurrency, with the most popular implementation being Celluloid. Celluloid provides a great abstraction that marries concurrency primitives to Ruby's object model. Celluloid can't guarantee that your code will be thread-safe or free from race conditions, but it wraps up best practices. I encourage you give Celluloid a try.

These problems that we're talking about aren't specific to Ruby or MRI. This is the reality of programming in a multi-core world. The number of cores on our devices is only going up, and MRI is still figuring out its answer to this situation. Despite its guarantees, the GIL's restriction on parallel execution seems like the wrong direction. This is part of MRI's growing pains. Other implementations, like JRuby and Rubinius, are running truly parallel with no GIL.

We're seeing lots of new languages that have concurrency abstractions built-in at the core of the language. The Ruby language doesn't have any of this, at least not yet. Another benefit of relying on abstraction is that the abstractions can improve their implementation, while your code remains unchanged. For example, if the implementation of Queue switched from relying on locks to using lock-free synchronization, your code would reap the benefits without any modification.

For the time being, Ruby developers should educate themselves about these issues! Learn about concurrency. Be aware of race conditions. Thinking about code as interleavings can help you reason about race conditions.

I'll leave off with a quote that's influencing much of the work being done in the larger field of concurrency today:

Don't communicate by sharing state; share state by communicating.

Using data structures for synchronization supports this; the Actor model supports this. This idea is at the core of the concurrency model of languages like Go, Erlang, and others.

Ruby needs to look to what's working in other languages and embrace it. As a Ruby developer, you can do this today by trying out and supporting some of these alternative approaches. With more people on board, these approaches could become the new standard for Ruby.

Thanks to Brian Shirai for reviewing a draft of this.

]]>
7
Peter Cooper http://twitter.com/peterc <![cdata[this Week in Ruby: Matz on Ruby 2.0, Numerous Conference CFPs, Tenderlove on define_method]]> http://www.rubyinside.com/?p=6043 2013年03月07日T12:44:43Z 2013年03月07日T12:44:43Z Welcome to this week’s roundup of Ruby news, articles, videos, and more, cobbled together from my e-mail newsletter, Ruby Weekly. Sorry these roundups have been missing for a couple of months, I've been focusing very heavily on the e-mail newsletters which are continuing to grow like crazy! :-) I hope to get back into blogging more soon.

Matz on Ruby 2.0 Matz spoke about Ruby 2.0 ('the happiest release ever') for 30 minutes at the Heroku Waza event a week ago and the video is already available to watch. He stresses that "Ruby 1.8 will die soon" and encourages everyone to upgrade. Read More

]]>
Welcome to this week’s roundup of Ruby news, articles, videos, and more, cobbled together from my e-mail newsletter, Ruby Weekly. Sorry these roundups have been missing for a couple of months, I've been focusing very heavily on the e-mail newsletters which are continuing to grow like crazy! :-) I hope to get back into blogging more soon.

Matz on Ruby 2.0
Matz spoke about Ruby 2.0 ('the happiest release ever') for 30 minutes at the Heroku Waza event a week ago and the video is already available to watch. He stresses that "Ruby 1.8 will die soon" and encourages everyone to upgrade.

Dynamic Method Definitions
Aaron 'tenderlove' Patterson says that "depending on your app, using define_method is faster on boot, consumes less memory, and probably doesn’t signigicantly impact performance" compared to eval-based techniques. (And he has the numbers to prove it.)

Steel City Ruby Conference 2013 CFP Now Open
Steel City Ruby takes places in Pittsburgh, PA on August 16-17 and the CFP is now open if you want to submit a talk. The Burlington Ruby Conference has a CFP open too, as does RubyConf India.

Reading

Inspecting Rails 4 using Ruby 2.0 and TracePoint
Matt Aimonetti shows off a practical use for Ruby 2.0's TracePoint execution tracing functionality.

Visualizing Memory Leaks in Ruby 1.9
Conrad Irwin on some clever work to extend ObjectSpace with a new find_references method to perform better analysis on object and memory usage on Ruby 1.9.

Parsing TOML in Ruby with Parslet
Recently, GitHub founder Tom Preston-Werner created an interesting INI-influenced 'TOML' format. In this series of posts, Nathan Witmer looks at what's involved in building a parser for TOML using the Parslet PEG parser construction library.

Introducing Ress: A System for Building Mobile Optimized Rails Apps
Matthew Robertson introduces his new system for building mobile-optimized Rails applications using semantic, media query-based device detection and server side component optimization.

Ruby 2.0 Walkthrough: The Best Bits
Some slides from my yet-to-be-released 'Ruby 2.0 Walkthrough' that quickly skim through what I consider to be the 'best bits' (and not just the headline features).

Rails + Ember.js
An introduction to the open source Ember.js JavaScript app framework for Rails developers.

Watching and Listening

Sinatra in SIX Lines: How to Do Crazy Stuff with Ruby
A talk by Konstantin Haase at Ruby Australia.

Libraries and Code

Phusion Passenger 4.0 Release Candidate 4
Leading Rack-based app deployment tool Passenger gets yet another step closer to the 4.0 release.

time-lord: A Human DSL for Time Expressions
A gem that gives you more human like expressions for time and space math. Get fun like 1.hour.ago.to_range and 200.minutes.ago.to_words

identity_cache: Opt-in Read-through ActiveRecord Caching, From Shopify
IdentityCache lets you specify how you want to cache your model objects, at the model level, and adds a number of convenience methods for accessing those objects through the cache. Uses Memcached as the backend cache store.

neg 1.1.0: A Small PEG Parser Library
"One could say it’s a small brother of Parslet."

Jobs

Web Application Developer for Big Nerd Ranch
Seeking smart, kind folks who want to make the world a little better through developing, training and writing about cutting-edge code.

JS / Ruby Developer at ReplayPoker (Full-Time, Remote)
Looking for a challenge? Our company is looking for a top-notch junior to mid level developer to join our small team and make a big difference!

Last but not least..

RTanque: A Robot Programming Game for Rubyists
Players program the 'brain' of a tank and then send their tank into battle with other bots. Based upon the Java project 'Robocode.'

]]>
1
Peter Cooper http://twitter.com/peterc <![cdata[a Simple Tour of the Ruby MRI Source Code with Pat Shaughnessy]]> http://www.rubyinside.com/?p=6020 2012年12月02日T17:03:26Z 2012年12月03日T15:20:31Z

I'm not in Ruby core or, well, even a confident C coder anymore, but I've long enjoyed digging in the Ruby MRI source code to understand weird behavior and to pick up stuff for my Ruby course.

Pat Shaughnessy is also a fan of digging around in Ruby's internals and has written some great posts like How Ruby Executes Your Code, Objects, Classes and Modules, and Exploring Ruby's Regular Expression Algorithm.

When Pat released his Ruby Under a Microscope book, I knew it would be right up my street! He digs into how objects are represented internally, why MRI, Rubinius and JRuby act in certain ways and, of course, "lots more."

I invited Pat to take a very high level cruise through the MRI codebase with me so we could share that knowledge with Ruby programmers who haven't dared take a look 'under the hood' and to show it's not as scary or pointless as it may seem. Read More

]]>
[フレーム]

I'm not in Ruby core or, well, even a confident C coder anymore, but I've long enjoyed digging in the Ruby MRI source code to understand weird behavior and to pick up stuff for my Ruby course.

Pat Shaughnessy is also a fan of digging around in Ruby's internals and has written some great posts like How Ruby Executes Your Code, Objects, Classes and Modules, and Exploring Ruby's Regular Expression Algorithm.

When Pat released his Ruby Under a Microscope book, I knew it would be right up my street! He digs into how objects are represented internally, why MRI, Rubinius and JRuby act in certain ways and, of course, "lots more."

I invited Pat to take a very high level cruise through the MRI codebase with me so we could share that knowledge with Ruby programmers who haven't dared take a look 'under the hood' and to show it's not as scary or pointless as it may seem.

It's 100% free so enjoy it above or on YouTube in 720p HD.

P.S. Pat is happy to do another video digging deeper into how Ruby actually takes your code and executes it and he's able to walk through the actual virtual machine for us. If the reaction to this video is good, we'll sit down again and see if we can do it! :-)

]]>
5
Peter Cooper http://twitter.com/peterc <![cdata[the Last Week in Ruby: A Great Ruby Shirt, RSpec Team Changes and a Sneaky Segfault Trick]]> http://www.rubyinside.com/?p=6016 2012年12月02日T01:48:08Z 2012年12月02日T01:48:08Z Welcome to this week's roundup of Ruby news cobbled together from my e-mail newsletter, Ruby Weekly.

Highlights include: A time-limited Ruby shirt you can order, a major change in the RSpec project, how to make Ruby 1.9.3 a lot faster with a patch and compiler flags, a sneaky segmentation fault trick, several videos, and a few great jobs.

Featured

The 'Ruby Guy' T-Shirt Grab a t-shirt with a cute 'Ruby Guy' mascot on the front in time for Christmas. Comes in both male and female styles in varying sizes. Only available till Thursday December 6 though as it's part of a temporary Teespring campaign (Note: I have no connection to this, it just looks cool.)

David Chelimsky Hands Over RSpec to New Project Leads After several years at the helm, David Chelimsky is handing over the reins to Myron Marston and Andy Lindeman for RSpec and rspec-rails respectively. Read More

]]>
Welcome to this week's roundup of Ruby news cobbled together from my e-mail newsletter, Ruby Weekly.

Highlights include: A time-limited Ruby shirt you can order, a major change in the RSpec project, how to make Ruby 1.9.3 a lot faster with a patch and compiler flags, a sneaky segmentation fault trick, several videos, and a few great jobs.

Featured

The 'Ruby Guy' T-Shirt
Grab a t-shirt with a cute 'Ruby Guy' mascot on the front in time for Christmas. Comes in both male and female styles in varying sizes. Only available till Thursday December 6 though as it's part of a temporary Teespring campaign (Note: I have no connection to this, it just looks cool.)

David Chelimsky Hands Over RSpec to New Project Leads
After several years at the helm, David Chelimsky is handing over the reins to Myron Marston and Andy Lindeman for RSpec and rspec-rails respectively. Thanks for all your hard work, David.

Upgrading to Rails 4: A Forthcoming Book (in Beta)
Andy Lindeman of the RSpec core team is working on a new book designed to bring you up to speed with Rails 4. It's in beta so you can support him now, if you like.

Reading

Making Your Ruby Fly
Andrei Lisnic demonstrates a few compile time 'tricks' you can use to make your MRI Ruby 1.9.3 faster. The benchmark results are compelling.

Avoiding the Tar Pits of Localization
Jeff Casimir gave a talk on the 'Ruby Hangout' about the trickiness of handling internationalization and localization and some tools and libraries you can use to help. Lots of notes here or you can watch the video.

Recovering From Segfaults in Ruby, The Sneaky Way
We've probably all seen the dreaded 'segmentation fault' from Ruby before. Charlie Somerville demonstrates a rather clever but sneaky way you can 'recover' from them in plain Ruby. As he says, you probably don't want to use this trick seriously.

Use Rails Until It Hurts
Evan Light pushes back a little against the recent wave of OO purity and, as DHH calls it, 'pattern vision.'

Speeding Things Up With jRuby
MRI's global interpreter lock prevents running code in parallel without forking the Ruby process. That's where JRuby can help.

Try RubyGems 2.0
Michal Papis demonstrates how you can give the forthcoming RubyGems 2.0 a spin using RVM.

Watching and Listening

Rapid Programming Language Prototypes with Ruby and Racc
At RubyConf 2012, Tom Lee demonstrated how you can use Racc, a LALR(1) parser generator that emits Ruby code from a grammar file, in the process of creating a simple programming language of your own.

A Tour Into An Oddity With Ruby's Struct Class
In which I look into why Struct.new(:foo?).new(true).foo? doesn't work, even though the Struct-produced class and its instances are valid. I dive into the MRI source code a bit to get to the bottom of things. 12 minutes in all.

RubyTapas 027: Macros and Modules
Avdi Grimm's latest Ruby screencast for non-subscribers to his Ruby video site.

A Rails 4.0 Roundup in 3 Videos
A summary and links to three Rails 4 related videos (all linked in RW before) by Marco Campana. A handy catch up if you didn't already.

Libraries and Code

Introducing the Rails API Project: Rails for API-only Applications
A set of tools to use Rails for building APIs for both heavy Javascript applications as well as non-Web API clients. This isn't entirely new but the project has now become more formally established.

Zuck: A Little Helper to Access Facebook's Advertising API
An early, prototype-stage gem but you may still find it useful.

Jobs

Blazing Cloud is looking for software artisans
to join us in handcrafting beautiful mobile experiences. We are looking for people who believe in a whole product-approach and agile development practices, and have a strong sense of quality.

Last but not least..

Come Speak at O'Reilly Fluent 2013
OK, it's slightly offtopic but I'm the co-chair for O'Reilly's JavaScript, HTML5 and browser technology event and I know many Rubyists are also involved in these areas. Our CFP is open until December 10 and we have lots of awesome stuff lined up.

]]>
0
Peter Cooper http://twitter.com/peterc <![cdata[the Split is Not Enough: Unicode Whitespace Shenigans for Rubyists]]> http://www.rubyinside.com/?p=5980 2012年11月26日T07:24:36Z 2012年11月26日T14:24:16Z

That code is legal Ruby! If you ran it, you'd see 8. How? There's a tale to tell..

The String with the Golden Space

I was on IRC in #nwrug enjoying festive cheer with fellow Northern Rubyists when ysr23 presented a curious problem.

He was using a Twitter library that returned a tweet, "@twellyme film", in a string called reply. The problem was that despite calling reply.split, the string refused to split on whitespace. Yet if he did "@twellyme film".split in IRB, that was fine.

International man of mystery Will Jessop suggested checking $; (it's a special global variable that defines the default separator for String#split). Read More

]]>

That code is legal Ruby! If you ran it, you'd see 8. How? There's a tale to tell..

The String with the Golden Space

I was on IRC in #nwrug enjoying festive cheer with fellow Northern Rubyists when ysr23 presented a curious problem.

He was using a Twitter library that returned a tweet, "@twellyme film", in a string called reply. The problem was that despite calling reply.split, the string refused to split on whitespace. Yet if he did "@twellyme film".split in IRB, that was fine.

International man of mystery Will Jessop suggested checking $; (it's a special global variable that defines the default separator for String#split). It was OK.

In an attempt to look smarter than I am, I suggested reply.method(:split).source_location to see if the String class had been monkey-patched by something annoying. Nope. (Though this is a handy trick if you do want to detect if anyone's tampered with something.)

Someone suggested Mr. Ysr23 show us reply.codepoints.to_a:

# reply.codepoints.to_a
 => [64, 116, 119, 101, 108, 108, 121, 109, 101, 160, 102, 105, 108, 109]

Something leapt out at me. Where was good old 32!? Instead of trusty old ASCII 32 (space) stood 160, a number alien to my ASCII-trained 1980s-model brain.

From Google with Love

To the Google-copter!

Aha! Non-breaking space. That's why split was being as useful as a chocolate teapot.

After an intense 23 seconds of discussion, we settled on a temporary solution for Mr. Ysr23 who, by this time, was busy cursing Twitter and all who sailed upon her:

reply.gsub(/[[:space:]]/, ' ').split

The solution is simple. Use the the Unicode character class [[:space:]] to match Unicode's idea of what whitespace is and convert all matches into vanilla ASCII whitespace. reply.split(/[[:space:]]+/) is another more direct option - we just didn't think of it at the time.

Quantum of Spaces

Solving an interesting but trivial issue wasn't where I wanted to end my day. I'd re-discovered an insidious piece of Unicode chicanery and was in the mood for shenanigans!

Further Googling taught me you can type non-breaking spaces directly on OS X with Option+Space. (You can do the homework for your own platform.)

I also knew Ruby 1.9 and beyond would let you use Unicode characters as identifiers if you let Ruby know about the source's encoding with a magic comment, so it was time for shenanigans to begin!

My first experiment was to try and use non-breaking spaces in variable names.

Cool! So what about variable names and method names?

What about without any regular printable characters in the identifiers at all?

And so we're back to where we started. A hideous outcome from a trivial weekend on IRC. But fun, nonetheless. Stick it in your "wow, nice, but totally useless" brain box.

A Warning

Please don't use this in production code or the Ruby gods will come and haunt you in your sleep. But.. if you want to throw some non-breaking spaces into your next pair programming session, conference talk, or job interview, just to see if anyone's paying attention, I'll be laughing with you. (And if you're a C# developer too, Andy Pike tells me that C# supports these shenanigans too.)

P.S. My Ruby 2.0 Walkthrough Kickstarter only has about 12 hours to go! Check it out if Ruby 2.0 is on your radar or you want a handy way to get up to speed when it drops in February 2013.

]]>
8
Peter Cooper http://twitter.com/peterc <![cdata[this Week in Ruby: Ruby 2.0 Refinements, Cost of GC::Profiler, and BritRuby Cancelled]]> http://www.rubyinside.com/?p=5975 2012年11月23日T16:56:27Z 2012年11月23日T16:56:27Z Welcome to this week’s roundup of Ruby news, articles, videos, and more, cobbled together from my e-mail newsletter, Ruby Weekly. If you've been celebrating Thanksgiving this week, I hope you're having a good break.

Highlights include: Charles Nutter on Ruby 2.0 refinements, the cancellation of the British Ruby Conference, and DHH's latest object instantiation (thanks Doug Renn).

Featured

Refining Ruby (or The Best Study of Ruby 2.0 Refinements Yet) I've editorialized the title somewhat but this article by Charles Nutter is a great look into the world of 'refinements' in Ruby 2.0, what they're intended for, and all of the challenges they throw up, both for developers and language implementers. Read More

]]>
Welcome to this week’s roundup of Ruby news, articles, videos, and more, cobbled together from my e-mail newsletter, Ruby Weekly. If you've been celebrating Thanksgiving this week, I hope you're having a good break.

Highlights include: Charles Nutter on Ruby 2.0 refinements, the cancellation of the British Ruby Conference, and DHH's latest object instantiation (thanks Doug Renn).

Featured

Refining Ruby (or The Best Study of Ruby 2.0 Refinements Yet)
I've editorialized the title somewhat but this article by Charles Nutter is a great look into the world of 'refinements' in Ruby 2.0, what they're intended for, and all of the challenges they throw up, both for developers and language implementers.

The British Ruby Conference.. Cancelled
It's a pretty long story but the British Ruby Conference, which I was getting rather excited about.. is no more. There's a statement as to why but if you want to join the melee of conversation, try here or here. Luckily other attempts are now afoot - news coming soon.

DHH's Latest Project: Colt Heinemeier Hansson
It's DHH's latest release :-) Congratulations to him and his growing family. And before anyone complains about having a human interest story here, cheer up a bit - it's Thanksgiving ;-)

Edge Rails Now Tested on Ruby 2.0 with Travis CI
Little to read but Ruby 2.0 is now most clearly on the edge Rails developers' radar.

Reading

Deploying Ruby Applications to AWS Elastic Beanstalk with Git
Just last week, Amazon announced Ruby support for its AWS Elastic Beanstalk semi-automated deployment and scaling system. This tutorial by Loren Segal fills in all the blanks by walking us through using it from start to finish with a Rails app.

Zen and The Art of Speaking at RubyConf 2012 - The dRuby Way
An excellent story and walkthrough about both preparing a talk for RubyConf 2012 and what happened while the speaker was there. More articles like this please.

The Cost of Ruby 1.9.3's GC::Profiler
James Golick presents an examination of the flaws in Ruby 1.9.3's included garbage collector instrumentation in his typically punchy style. Luckily he presents a potential solution too: GC::BasicProfiler.

Is Your Application Running with Ruby - Slow?
Two developers moved a large Ruby webapp between two machines and experienced a 50% drop in performance. Why? Clue: It was something to do with RVM.

A 2012 Mac Setup for Ruby development
We see articles like this quite often but there are a lot of handy links here despite not being particularly Ruby focused.

A Lightweight 'CMS' Using Ruby and Google Drive
An interesting approach to content management. Let users enter text in a Google Drive spreadsheet, grab it with Ruby, and use the data to create your content or templates locally.

A 'yield' Gotcha Every Ruby Developer Should Be Aware of
It's not a true yield gotcha but is something you might trip over nonetheless regarding earlier than expected returns. Luckily, 'ensure' blocks help save the day.

Profiling Ruby (or How I Made Rails Start Up Faster)
Four steps: measure, find the problem, fix, and repeat.

Watching and Listening

Guest User Records - RailsCasts
Ryan Bates is back with another Rails Cast, this time demonstrating how to create a 'temporary guest record' in a Rails app so users can try out apps without filling in their information up front.

Matz Speaking at LinkedIn about Ruby
Back in October, Matz spoke at LinkedIn about his background, Ruby's history, and his current work. I enjoyed this.

Libraries and Code

Convert Syck to Psych YAML Format
Change has been afoot with Ruby's attitude to YAML parsing for a while now but the shift from Syck to Psych can still cause issues. If you still have legacy Syck-produced YAML files around that are causing problems, this code might help.

Daybreak: A Simple Key/Value Store for Ruby
Very lightweight and very Ruby (in the best possible way).

chruby: Changes The Current Ruby
An 'ultra-minimal' (around 80 lines) alternative to RVM and rbenv. chruby allows one to install rubies into /usr/local/$ruby, /opt/$ruby or ~/.rubies/$ruby but install gems into ~/.gem/$ruby/$version. chruby only modifies $PATH, $GEM_HOME and $GEM_PATH, and does not hook cd or rely on shims.

Jobs

Last but not least..

Giles Bowkett: 'I Wrote An eBook In A Week'
Being silly enough to not send me a copy for review or give me a title, all I can do is say Giles has written an interesting sounding book about how 'DHH gets OOP wrong' but why that's OK. It costs money but hopefully we'll see some reviews soon. He does have a no-quibble refund policy, however, and his writing is always an eye opener.

]]>
0
Peter Cooper http://twitter.com/peterc <![cdata[this Week in Ruby: MRI 1.9.3-p327, Rails 3.2.9, Capybara 2.0, and the Fukuoka Ruby Award]]> http://www.rubyinside.com/?p=5970 2012年11月15日T16:20:36Z 2012年11月15日T16:20:36Z Welcome to this week’s roundup of Ruby news, articles, videos, and more, cobbled together from my e-mail newsletter, Ruby Weekly.

Highlights include: MRI 1.9.3-p327, Rails 3.2.9, Capybara 2.0, and the Fukuoka Ruby Award.

Featured

Ruby 1.9.3-p327 Released: Fixes a Hash-Flooding DoS Vulnerability Carefully crafted strings can be used in a denial of service attack on apps that parse strings to create Hash objects by using the strings as keys. This new patch level release of 1.9.3 counters the issue.

2013 Fukuoka Ruby Award Competition Each year Matz and the Government of Fukuoka in Japan run an award for Ruby programs. Submit by November 30th to enter - it doesn't have to be an all new app either. Read More

]]>
Welcome to this week’s roundup of Ruby news, articles, videos, and more, cobbled together from my e-mail newsletter, Ruby Weekly.

Highlights include: MRI 1.9.3-p327, Rails 3.2.9, Capybara 2.0, and the Fukuoka Ruby Award.

Featured

Ruby 1.9.3-p327 Released: Fixes a Hash-Flooding DoS Vulnerability
Carefully crafted strings can be used in a denial of service attack on apps that parse strings to create Hash objects by using the strings as keys. This new patch level release of 1.9.3 counters the issue.

2013 Fukuoka Ruby Award Competition
Each year Matz and the Government of Fukuoka in Japan run an award for Ruby programs. Submit by November 30th to enter - it doesn't have to be an all new app either. The grand prize is 1 million yen (about 12,000ドル).

Capybara 2.0.0 Released: The Acceptance Test Framework for Webapps
Not backwards compatible with Capybara 1.x so be careful and read the notes. It also drops support for Ruby 1.8.

Reading

Printing 'Hello, World' in Style (Concurrently)
Daniel Szmulewicz looks at what's involved in using Celluloid and two actors to print out 'Hello, World'.

Matz Is Not A Threading Guy
Jesse Storimer talks about the status of concurrency in Ruby and Matz's opinions in a Q+A session at RubyConf. Reinforcing the status quo, Matz said: 'Using multiple processes is the best way to do concurrency in MRI for the near future.'

rspec-rails and Capybara 2.0: What You Need to Know
Andy Lindeman of the RSpec core team talks about the new Capybara 2.0 release and what you need to be aware of when using it with RSpec and Rails.

Why Ruby Class Methods Resist Refactoring
Bryan Helmkamp demonstrates why he thinks class methods are much trickier to refactor than instance methods.

Reference Graphs as Tools for Refactoring
A quick look at using graphs of references in order to refactor Ruby code.

Watching and Listening

How I Set out to Benchmark an Algorithm and Ended Up Fixing Ruby
Joshua Ballanco wanted to build a delegation library but got lured into the worlds of benchmarks and garbage collectors.

Ten Things You Didn't Know You Could Do in Ruby
A month ago, we linked to the slidedeck of James Edward Gray II's Aloha on Rails talk with 101 various Ruby tricks and code snippets. Now the video is available too! Enjoy.

The Ruby Rogues on Documenting Code
The Ruby Rogues tackle a sore subject: documentation.

Libraries and Code

ruby-lint: Static Code Analysis and Linter for Ruby
Currently a prototype and work in progress so your mileage may vary. It makes it possible for developers to detect errors such as undefined or unused variables and the use of non existing methods.

Spinel: A New, 'Ruby-Infused' Open Source Game Engine
Spinel is a new open source game engine still under development that uses 'mruby' (the embeddable Ruby interpreter Matz is currently working on) as its scripting layer while leaning on speedy C/C++ under the hood.

Version Cake: An Unobtrusive Way to Version APIs in Your Rails App
Easily version views with their API version in the filename (e.g. index.v3.xml.builder). The cool part is if a request comes in for a different version, the closest version will be used.

Jobs

Test Driven JavaScript and Ruby Developer [San Francisco and Santa Monica, CA]
Carbon Five builds web and mobile products for startups, institutional companies and non-profit organizations using a finely tuned agile process with cutting edge tools and technology. Join a team of seasoned pros in a highly-collaborative environment and work on a new project every couple of months.

Last but not least..

Write Faster Rails Tests: Insights via E-mail
Get an infrequent e-mail from Thoughbot's Ben Orenstein packed with battle tested advice for speeding up your Rails apps' tests.

]]>
0

AltStyle によって変換されたページ (->オリジナル) /