user2015453
user2015453

Reputation: 5104

Why isn't this simple Ruby code working in HAML?

If I run this simple Ruby code regularly, it works fine:

class String
  def add_two
    self + "2"
  end
end
puts "hello".add_two

It prints "hello2" as it should. But this fails:

:ruby
  class String
    def add_two
      self + "2"
    end
  end
  puts "hello".add_two

This code produces an error:

NoMethodError at /
undefined method `add_two' for "hello":String

Any ideas what's wrong?

(Not sure if it matters, but I'm using HAML with Sinatra, which is running on Apache with the Passenger module.)

Upvotes: 2

Views: 128

Answers (2)

User
User

Reputation: 14873

I would suggest that String is in another namespace and therefor another class.

What happens with that?

class ::String

Upvotes: 2

Paul Fioravanti
Paul Fioravanti

Reputation: 16793

I put your code as is into one of my Haml views in a Rails app and I got a different error to you:

SyntaxError at /
class definition in method body

So I wondered whether it was Haml's :ruby filter that was complaining, but since it "Parses the filtered text with the normal Ruby interpreter", it seemed unlikely. So, I searched for more info about the error and found references (see below) that led me to this, which works (but, really, should never be used):

:ruby
  String.module_eval do
    def add_two
      self + "2"
    end
  end
  puts "hello".add_two

References:

Upvotes: 1

Related Questions