Best ruby questions in October 2010

Using God to monitor Unicorn - Start exited with non-zero code = 1

16 votes

I am working on a God script to monitor my Unicorns. I started with GitHub's examples script and have been modifying it to match my server configuration. Once God is running, commands such as god stop unicorn and god restart unicorn work just fine.

However, god start unicorn results in WARN: unicorn start command exited with non-zero code = 1. The weird part is that if I copy the start script directly from the config file, it starts right up like a brand new mustang.

This is my start command:

/usr/local/bin/unicorn_rails -c /home/my-linux-user/my-rails-app/config/unicorn.rb -E production -D

I have declared all paths as absolute in the config file. Any ideas what might be preventing this script from working?

I haven't used unicorn as an app server, but I've used god for monitoring before.

If I remember rightly when you start god and give your config file, it automatically starts whatever you've told it to watch. Unicorn is probably already running, which is why it's throwing the error.

Check this by running god status once you've started god. If that's not the case you can check on the command line what the comand's exit status is:

/usr/local/bin/unicorn_rails -c /home/my-linux-user/my-rails-app/config/unicorn.rb -E production -D; echo $?;

that echo will print the exit status of the last command. If it's zero, the last command reported no errors. Try starting unicorn twice in a row, I expect the second time it'll return 1, because it's already running.

Are types and OO coupled ?

15 votes

Trying to understand if types imply OO and vice versa.

Questions:

  • What exactly is a type ?

  • Can a class in ruby be called a 'type'.

  • In javascript, the native functions/objects like Array,String,Function ... Are they types ?

  • Is a C struct a type ?

  • How is it that a language can be typed even when it doesn't support OO ? For e.g. Haskell. Is it that types in such langs are "data" types without behavior(methods) in objects/classes in OOPL ? What are the significant differences in types between langs that have types but no OO and langs that support OO.

  • If classes/objects are types, doesn't OO imply types ?

  • Can you have a type system without the typical hierarchies seen in OO langs ?

  • Since clojure supports type hints, can it be called typed in some sense? it is not statically typed.

  • Do the words 'untyped' and 'dynamically typed' mean the same thing ?

A static type is a property of portion of a program (usually an expression) that the type checker will attempt to prove or disprove without executing the program, possibly while simultaneously inferring the property. (Actually, this is a bit off, dependent types and staged compilation make the truth a bit fuzzier than this). Seen broadly enough, a dynamically typed language has one static type - the type of syntactically valid expressions.

A dynamic type is a property of an "object" (not necessarily an OO object) that the runtime will check automatically during program execution. Every mainstream statically typed language has some dynamic types...e.g. the divide function is statically defined to take two numbers and return a number but dynamically defined such that the second number cannot be zero. There are statically typed languages for which "non-zero number" can be a statically proven type. In many statically typed languages (e.g. Java) non-null is a dynamic type whereas in Haskell it's a static type. Etc.

The two are somewhat related (they're both ways to prevent undefined behavior) but also so totally different that it is a source of confusion that the word "type" is used to mean both.

Both static and dynamic type systems predate OO and both have excellent non-OO languages to represent them (e.g. Scheme and SML). In fact, they predate computer programming as we know it. See the untyped and simply typed lambda calculii which date to the 1930's and 40's.

For a more in depth discussion about the differences see: http://web.archive.org/web/20080822101209/http://www.pphsg.org/cdsmith/types.html

For one approach to looking at some properties of both static and dynamic types see: http://james-iry.blogspot.com/2010/05/types-la-chart.html

Do dynamically typed and untyped mean the same thing? Well...untyped comes from the untyped lambda calculus. It's called untyped in contrast to other lambda calculii like the simply typed lambda calculus which have static types. So certainly dynamically typed languages are untyped in that sense. But...

The untyped lambda calculus, unlike a "real" programming language, has the property that any syntactically valid expression can "make progress" without any need to test for any properties that might lead to undefined behavior. There's no equivalent of dividing by zero, dereferencing a null, or sending a message to an object that can't handle it. So one could make the argument that the untyped LC does not have a dynamic type system even though it is untyped.

Is there an advantage to running JRuby if you don't know any Java?

14 votes

I've heard great things about JRuby and I know you can run it without knowing any Java. My development skills are strong, Java is just not one of the tools I know. It's a massive tool with a myriad of accompanying tools such as Maven/Ant/JUnit etc.

Is it worth moving my current Rails applications to JRuby for performance reasons alone? Perhaps if I pick up some basic Java along side, there can be so added benefits that aren't obvious such as better debugging/performance optimization tools?

Would love some advice on this one.

I think you pretty much nailed it:

JRuby is just yet another Ruby execution engine, just like MRI, YARV, IronRuby, Rubinius, MacRuby, MagLev, SmallRuby, Ruby.NET, XRuby, RubyGoLightly, tinyrb, HotRuby, BlueRuby, Red Sun and all the others.

The main differences are:

  • portability: for example, YARV is only officially supported on x86 32 Bit Linux. It is not supported on OSX or Windows or 64 Bit Linux. Rubinius only works on Unix, not on Windows. JRuby OTOH runs everywhere: desktops, servers, phones, App Engine, you name it. It runs on the Oracle JDK, OpenJDK, IBM J9, Apple SoyLatte, RedHat IcedTea and Oracle JRockit JVMs (and probably a couple of others I forgot about) and also on the Dalvik VM. It runs on Windows, Linux, OSX, Solaris, several BSDs, other proprietary and open Unices, OpenVMS and several mainframe OSs, Android and Google App Engine. In fact, on Windows, JRuby passes more RubySpec tests than "Ruby" (meaning MRI or YARV) itself!

  • extensibility: Ruby programs running on JRuby can use any arbitrary Java library. Through JRuby-FFI, they can also use any arbitrary C library. And with the new C extension support in JRuby 1.6, they can even use a large subset of MRI and YARV C extensions, like Mongrel for example. (And note that "Java" or "C" library does not actually mean written in those languages, it only means with a Java or C API. They could be written in Scala or Clojure or C++ or Haskell.)

  • tooling: whenever someone writes a new tool for YARV or MRI (like e.g. memprof), it turns out that JRuby already had a tool 5 years ago which does the same thing, only better. The Java ecosystem has some of the best tools for "runtime behavior comprehension" (which is a term I just made up, by which I mean much more than just simple profiling, I mean tools for deeply understanding what exactly your program does at runtime, what its performance characteristics are, where the bottlenecks are, where the memory is going, and most importantly why all of that is happening) and visualization available on the market, and pretty much all of those work with JRuby, at least to some extent.

  • deployment: assuming that your target system already has a JVM installed, deploying a JRuby app (and I'm not just talking about Rails, I also mean desktop, mobile, other kinds of servers) is literally just copying one JAR (or WAR) and a double-click.

  • performance: JRuby has much higher startup overhead. In return you get much higher throughput. In practice, this means that deploying a Rails app to JRuby is a good idea, as is running your integration tests, but for developer unit tests and scripts, MRI, YARV or Rubinius are better choices. Note that many Rails developers simply develop and unit test on MRI and integration test and deploy on JRuby. There's no need to choose a single execution engine for everything.

  • concurrency: JRuby runs Ruby threads concurrently. This means two things: if your locking is correct, your program will run faster, and if your locking is incorrect, your program will break. (Unfortunately, neither MRI nor YARV nor Rubinius run threads conurrently, so there's still some broken multithreaded Ruby code out there that doesn't know it's broken, because obviously concurrency bugs can only show up if there's actual concurrency.)

  • platforms (this is somewhat related to portability): there are some amazing Java platforms out there, e.g. the Azul JCA with 768 GiBytes of RAM and 864 CPU cores specifically designed for memory-safe, pointer-safe, garbage-collected, object-oriented languages. Android. Google App Engine. All of those run JRuby.

Installing Ruby on Ubuntu 10.10 using RVM, problem with gem

10 votes

I've decided to start fresh with ubuntu 10.10. I started with installing git and then installing rvm from the git repo. everything worked fine and I compiled and install ruby 1.8.7 and ruby 1.9.2
the gem is also installed and I run gem -v
but when run gem list or gem install rake I get the following error

ERROR:  Loading command: list (LoadError)
no such file to load -- zlib
ERROR:  While executing gem ... (NameError)
uninitialized constant Gem::Commands::ListCommand

any idea how to solve this issue? I also tried sudo apt-get install zlib1g zlib1g-dev build-essential libpq-dev with no luck

When using rvm you can simple do steps that are shown here: link text

$ rvm package install zlib
$ rvm remove 1.9.2
$ rvm install 1.9.2 --with-zlib-dir=~/.rvm/usr

How unique is PHP's __autoload()?

10 votes

PHP's __autoload() (documentation) is pretty interesting to me. Here's how it works:

  • You try to use a class, like new Toast_Mitten()(footnote1)
  • The class hasn't been loaded into memory. PHP pulls back its fist to sock you with an error.
  • It pauses. "Wait," it says. "There's an __autoload() function defined." It runs it.
  • In that function, you have somehow mapped the string Toast_Mitten to classes/toast_mitten.php and told it to require that file. It does.
  • Now the class is in memory and your program keeps running.

Memory benefit: you only load the classes you need. Terseness benefit: you can stop including so many files everywhere and just include your autoloader.

Things get particularly interesting if

1) Your __autoload() has an automatic way of determining the file path and name from the class name. For instance, maybe all your classes are in classes/ and Toast_Mitten will be in classes/toast_mitten.php. Or maybe you name classes like Animal_Mammal_Weasel, which will be in classes/animal/mammal/animal_mammal_weasel.php.

2) You use a factory method to get instances of your class.

$Mitten = Mitten::factory('toast');

The Mitten::factory method can say to itself, "let's see, do I have a subclass called Toast_Mitten()? If so, I'll return that; if not, I'll just return a generic instance of myself - a standard mitten. Oh, look! __autoload() tells me there is a special class for toast. OK, here's an instance!"

Therefore, you can start out using a generic mitten throughout your code, and when the day comes that you need special behavior for toast, you just create that class and bam! - your code is using it.

My question is twofold:

  • (Fact) Do other languages have similar constructs? I see that Ruby has an autoload, but it seems that you have to specify in a given script which classes you expect to use it on.
  • (Opinion) Is this too magical? If your favorite language doesn't do this, do you think, "hey nifty, we should have that" or "man I'm glad Language X isn't that sloppy?"

1 My apologies to non-native English speakers. This is a small joke. There is no such thing as a "toast mitten," as far as I know. If there were, it would be a mitten for picking up hot toast. Perhaps you have toast mittens in your own country?

Both Ruby and PHP get it from AUTOLOAD in Perl.

Note that the AutoLoader module is a set of helpers for common tasks using the AUTOLOAD functionality.

What alternatives to IRB are there?

9 votes

In the python world, there are a number of alternative python interpreters that add cool additional features. One particularly useful example is bpython, which adds dynamic syntax highlighting, automatically pulls documentation, and displays live autocomplete information. In the Ruby world, I have yet to uncover any projects which add to the basic IRB interpreter even a subset of these features. Am I just not looking hard enough, or is this just something the Ruby community is lacking?

What a coincidence. Rubyflow just yesterday announced the irbtools gem, which is a meta-gem containing lots of cool irb enhancement gems. It contains:

Features (pasted from the page):

■Colorized by wirble and put out as comment by irb_rocket
■Nice IRB prompt and IRB’s auto indention (still simple, but still far better than none)
■FileUtils: ls, cd, pwd, ln_s, rm, mkdir, touch, cat
■Many debugging helpers: ap, q, o, c, y, Object#m, Object#d 
■ap – awesome_print
■q – like p, but on one line
■Object#m – ordered method list (takes integer parameter: level of nesting)
■Objedt#d – puts the object, returns self (using tap)
■“Magical” information constants: Info, OS, RubyVersion, RubyEngine 
■OS.windows?
■RubyEngine.jruby?
■RubyVersion.is.at_least? 1.9
■guessmethod automatically corrects typing mistakes or suggests alternative methods (method_missing hook)
■Clipboard features: copy and paste 
■also available: copy_input and copy_output for session history
■Call vim (or another supported editor) to edit a file, close it and it gets loaded into your current irb session, powered by interactive_editor
■Highlight a string with colorize('string') or a file with ray('path'), powered by coderay
■Displays ActiveRecord database entries as tables with hirb
■Restart irb with reset! or change the Ruby version with the use method and rvm!
■Includes the current directory in the load path (was removed in 1.9.2 for security reasons, but is pretty annoying in irb)
■Shorter requiring like this: rq:mathn
■Access to a lot of more commands with boson – call commands to get started

There are nice screenshots on the irbtools page.

Rails tests can't find test_helper

8 votes

I'm trying to run individual tests through ruby test/unit/mytest.rb, but I always get a "no such file to load - test_helper" error. Google brought up a few suggestions, but none of them worked for me. I'm running Rails 3.0, Ruby 1.9.2 (through RVM) on Ubuntu 10.10

Here's what I've tried so far - any suggestions really appreciated

  • Changed the "require test_helper" to "require File.dirname(FILE) + "/../test_helper" " in test/unit/mytest_test.rb. It brings back " no such file to load -- test/unit/../test_helper"
  • Tried running rvm test/unit/mytest_test.rb Same as above
  • Tried running ruby -I test/unit/mytest_test.rb. No messages to the terminal. After about 5 minutes waiting for something to happen, ctrl+c'd out of it

Any suggestions very appreciated - I'm stumped.

ruby 1.9.2 removed ".", the current directory, from the load path. I have to do this to get it to work:

require 'test_helper'

and call it like:

ruby -I. unit/person_test.rb 

Ruby task: joining numbers to intervals

8 votes

I've got an array of uniq numbers. Like this: [1,2,3,4,7,8,10,12]. It can be unsorted. What I need is to get intevals for this array:

intervals_for [1,2,3,4,7,8,10,12]
#=> "1-4, 7-8, 10,12"

I've got my own solution:

def intervals_for(array)
  array.sort!
  new_array = []
  array.each do |a|
    if new_array.last and a == new_array.last.last+1
      new_array.last << a
    else
      new_array << [a]    
    end
  end
  new_array.map{|a| a.size > 1 ? "#{a.first}-#{a.last}" : a.first}.join(", ")
end

But I think somewhere here is more clean solution

here's mine, using ver 1.9.1

def torange(a)
  r=[];s=a[0]
  a.uniq.sort!.each_cons(2) do |a|
      r<<[s,a[0]] and s=a[1] if a[1]-a[0]!=1
  end
  left=a.index(s)
  r<<[a[left..-1][0],a[left..-1][-1]]
end

torange([1,2,3,4,7,8,10,12]).each do |x|
  puts x[0]==x[1] ? "#{x[0]}" : "#{x[0]}-#{x[1]}"
end

output

$ ruby test.rb
1-4
7-8
10
12

What will a Python programmer gain by learning Ruby?

8 votes

I am going to be learning Ruby, Haskell and Prolog at university. Now, I'm wondering what should get most of my attention. I have half a year to do all three, which means I need to decide on one language to get my extracurricular time. The others I will learn just enough to do very good in the course.

I am familiar enough with Haskell and Prolog to know that learning them will teach me a few very important concepts of computer science. I'm not so sure about ruby.

Going through a few tutorials and introductions, I get the impression that ruby is a lot of shallow magic. Now I'm asking the ruby people: What will I have gained, should I decide never to use it again, after I've spent half a year learning it, that Python didn't already teach me.

This question is not intended to "make the case" for ruby, although I realise this is a potential topic of great argumentation.

I use Python for all my CS work now. I have done quite a bit of functional programming with it as well. I am also, already, quite familiar with object oriented programming (in Java, Python and C#). And I shall, as I said, do some Logical programming with Prolog.

What then is left for Ruby to teach me?

To further dilute the question:

  • I'm not interested in writing fun programs, or cool web applications. I'm just interested in the Computer Science bits. Implementing algorithms, data structures and so on. (Although having fun surely won't hurt)

  • Ideally, concepts discussed need to be learnable in about 1.000 hours.

  • I'm not at all interested in Rails. Any technology that hides complexity is, in this case, detrimental.

I can't help this question being argumentative. But an ideal answer to this question will mention a profoundly important concept of theoretical computer science that ruby helps the programmer use and understand in order to gain scientifically adjuvant knowledge.

To candidates I came up with are Meta-programming and Multi-threading. I don't know if ruby is particularly great to learn either of them.

Edit 1:

  • Being marketable is not a requirement. I'll worry about that after i've got my degrees.

  • I really don't have any time to learn yet another language. Learning Ruby, Haskell and Prolog is required of me, not a choice. And I want to do the best job I can.

For the most part, nothing. Most of Ruby's strengths/weaknesses are the same as Python's, except that Ruby is slightly more "functional". However if you have Haskell as an option, much more can be learned about functional programming from Haskell than from Ruby.

Second, if you're looking at things from a theoretical computer science perspective, then Ruby is far from a language of choice. Ruby and a lot of its libraries break a lot of standard OOP dogma which I believe many academics would find repulsive (this is based mainly on my chats about languages with various professors).

From an academic perspective I think Haskell would have the most appeal to you. If you're interested in AI or logic, then Prolog is also an excellent choice.

How to reference an embedded document in Mongoid?

7 votes

Using Mongoid, let's say I have the following classes:

class Map
  include Mongoid::Document

  embeds_many :locations
end

class Location
  include Mongoid::Document

  field :x_coord, :type => Integer
  field :y_coord, :type => Integer

  embedded_in      :map, :inverse_of => :locations
end


class Player
  include Mongoid::Document

  references_one   :location
end

As you can see, I'm trying to model a simple game world environment where a map embeds locations, and a player references a single location as their current spot.

Using this approach, I'm getting the following error when I try to reference the "location" attribute of the Player class:

Mongoid::Errors::DocumentNotFound: Document not found for class Location with id(s) xxxxxxxxxxxxxxxxxxx.

My understanding is that this is because the Location document is embedded making it difficult to reference outside the scope of its embedding document (the Map). This makes sense, but how do I model a direct reference to an embedded document?

Because Maps are their own collection, you would need to iterate over every Map collection searching within for the Location your Player is referenced.

You can't access embedded documents directly. You have to enter through the collection and work your way down.

To avoid iterating all of the Maps you can store both the Location reference AND the Map reference in your Player document. This allows you to chain criteria that selects your Map and then the Location within it. You have to code a method on your Player class to handle this.

def location
  self.map.locations.find(self.location_id)
end

So, similar to how you answered yourself except you could still store the location_id in your player document instead of using the coord attribs.

Another way would be to put Maps, Locations, and Players in their own collections instead of embedding the Location in your Map collection. Then you could use reference relationships without doing anything fancy... however your really just using a hierarchical database likes it's a relational database at this point...

Rails tutorial for the dumbest person in the world (me)?

6 votes

It is very difficult for me to find Rails tutorials (or books are also great) for my requirements:

  1. Stupidity
  2. Ruby 1.9 or lastest 1.8
  3. MySQL
  4. A Game (simple roll play)
  5. JQuery front

Thanks you!

The Rails Guides are great and easy on the eyes too.

Is there a good, solid reference for proper RDoc syntax?

6 votes

I'm looking for a good, solid reference for proper RDoc syntax. Recommendations? I can't seem to find anything that clearly shows:

  1. How to document class methods and their parameters
  2. How to document what a class or class method does.

Update 1

I found a similar question with a great answer and I wanted to reference it here: Good tutorials on how to use rdoc?

The documentation at rdoc.rubyforge.org seems to be more complete than the version at rdoc.sourceforge.net (which incidentally has a 2003 modified date).

Also, there is a great source of examples: the Ruby core and stdlib documentation. For example, take a look at one of the class methods from the File class:

File.atime(file_name) => time

Returns the last access time for the named file as a Time object).

File.atime("testfile") #=> Wed Apr 09 08:51:48 CDT 2003

You can view the original source code, including the RDoc markup, by clicking on the first line (in the actual RDoc page, not in the quote I included in this answer). In this case, the method was implemented in C, but the RDoc formatting is the same as if it was implemented in Ruby:

/*
 *  call-seq:
 *     File.atime(file_name)  =>  time
 *  
 *  Returns the last access time for the named file as a Time object).
 *     
 *     File.atime("testfile")   #=> Wed Apr 09 08:51:48 CDT 2003
 *     
 */

From this you can see that call-seq: lets you replace the method name and parameters with text of your choosing, which is very useful for class methods. It also shows how you can display example code in a monospaced font by indenting it, similar to Markdown.

Best way to teach yourself Ruby?

6 votes

I have a decent amount of web development and programming experience with C, C++ and several markup languages. In order to expand my knowledge I've decided to learn Ruby and I'm wondering what you guys recommend as being the best way to teach it to yourself. I took a quick browse through the books available at Amazon but nothing immediately jumped out at me.

Thanks a lot in advance, I really appreciate it.

I've introduced a few guys to Ruby in the last couple of weeks, here are some of the things I have recommended that they've liked a lot:

  • Learn to Program
    • More for the inexperienced programmer, though. So in this case it's not a fit.
  • Try Ruby
    • Try Ruby in your browser! General introduction.
  • Ruby Koans
    • Make tests pass. Great way to learn the Ruby syntax.
  • Ruby Warrior
    • Another fun way like Ruby Koans to learn Ruby.

I also recommended always having The Ruby Programming Language and/or Read Ruby 1.9 at their side as reference.

Once you got the basic syntax covered, dive into some Web fun with something simple like Sinatra. After all, the best way to learn a language is to start using it.

Ruby 1.9 Array.to_s behaves differently?

6 votes

i wrote a quick little application that takes a base file of code with some keywords, a file of replacements for the keywords, and outputs a new file with the keywords replaced.

When i was using Ruby 1.8, my outputs would look fine. Now when using Ruby 1.9, my replaced code has the newline characters in it instead of line feeds.

For example, i see something like:

["\r\nDim RunningNormal_1 As Boolean", "\r\nDim RunningNormal_2 As Boolean", "\r\nDim RunningNormal_3 As Boolean"]

instead of:

Dim RunningNormal_1 As Boolean
Dim RunningNormal_2 As Boolean
Dim RunningNormal_3 As Boolean

i use a hash of replacements {"KEYWORD"=>["1","2","3"]} and an array of the replaced lines.

i use this block to finish the replacement:

resultingLibs.each do |x|
  libraryString.sub!(/(<REPEAT>(.*?)<\/REPEAT>)/im) do |match|
    x.each do |individual|
      individual.to_s 
    end
  end
end
#for each resulting group of the repeatable pattern,
#  
#Write out the resulting libs to a combined string

My hunch is that i'm printing out the array instead of the strings within the array. Any suggestions on a fix. When i debug and print my replaced string using puts, the output looks correct. When i use the to_s method (which is how my app writes the output to the output file), my output looks wrong.

A fix would be nice, but what i really want to know is what changed between Ruby 1.8 and 1.9 that causes this behavior. Has the to_s method changed somehow in Ruby 1.9?

*i'm inexperienced in Ruby

Yes, you're calling to_s on an array of strings. In 1.8 that is equivalent to calling join, in 1.9 it is equivalent to calling inspect.

To get the behavior you want in both 1.8 and 1.9, call join instead of to_s.