views:

140

answers:

2

I have been digging through some ruby gem code and i came across these and not sure what they means

def success?
  !!@success
end

def failure?
  !@success
end

cattr_accessor :test_response

and lastly this chunk of code

class_inheritable_accessor :attributes
self.attributes = []

def self.attribute(name, options={})
  top_level_name = name.to_s.split(".").last.underscore
  define_method top_level_name do
    read_attribute name
  end

If you only know one or two thats fine ...i just want to understand them...thanks

+3  A: 

What parts specifically don't you understand in the second part of code?

The methods success? and failure? in the first snippet return boolean values (true/false) in relation to the @success instance attribute.

cattr_accessor creates a read/write class attribute called test_response

Here's a little more information which is also explained better: http://apidock.com/rails/Class/cattr_accessor

Jim Schubert
+6  A: 

!! is a "cast to boolean". ! negates a value, !! negates the negated value. Hence !! turns any value into a boolean.

> 5
=> 5
> !5
=> false
> !!5
=> true
> !!5 == true
=> true
deceze
Wouldn't just '!' be the 'cast to boolean', "!!" just negated the first '!' ( which casts the value to boolean )
Rishav Rastogi
@Rishav "cast to boolean" as in "cast to *equivalent* boolean value". Not sure if `!` could be called a cast, since the value is completely opposite. That's putting a really fine point on it though.
deceze
@Rishav: if `@@success` is a string, `x = 'TRUE';!!x;` would yield `true` instead of `'TRUE'`. The `!@success` would return `false` but issue a warning.
Jim Schubert
thanks!! got it
Rishav Rastogi