Forum: Ruby CONST initialization...

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
9f4e11fd04ca1e5a56d00ff3531104ed?d=identicon&s=25 Jean Nibee (jeannibee)
on 2007-07-05 21:12
How come this works when I access Orders::PAYMENT_TYPES

>>>>>>>>>> CODE
class Order < ActiveRecord::Base
  PAYMENT_TYPES = [
    [ "Check", "check" ],
    [ "Credit card", "cc" ],
    [ "Purchase order", "po" ]
  ]

  has_many :line_items

  validates_presence_of :name, :address, :email, :pay_type
  validates_inclusion_of :pay_type, :in => PAYMENT_TYPES.map {|disp,
value| value}

end
<<<<<<<<<< CODE

But this doesn't:

>>>>>>>>>> CODE
class Order < ActiveRecord::Base
  has_many :line_items

  validates_presence_of :name, :address, :email, :pay_type
  validates_inclusion_of :pay_type, :in => PAYMENT_TYPES.map {|disp,
value| value}

  PAYMENT_TYPES = [
    [ "Check", "check" ],
    [ "Credit card", "cc" ],
    [ "Purchase order", "po" ]
  ]

end
<<<<<<<<<< CODE

Error thrown:
/usr/lib/ruby/gems/1.8/gems/activesupport-1.4.2/lib/active_support/dependencies.rb:477:in
`const_missing'

I have moved the PAYMENT_TYPES map around and it even is okay if it's
after the has_many :item_lines accessor, but not if it's after the
'validation' accessors.

Thanks.
Ef3aa7f7e577ea8cd620462724ddf73b?d=identicon&s=25 Rob Biedenharn (Guest)
on 2007-07-05 21:52
(Received via mailing list)
On Jul 5, 2007, at 3:12 PM, Jean Nibee wrote:
>
> Thanks.

I think you've answered your own question, but you might not
understand why.  The ruby interpreter is "executing" each line within
the class definition as it is encountered.  If there's no
PAYMENT_TYPES when the validates_inclusion_of line is reached, it
really doesn't matter that it *does* appear later in the class
definition.

-Rob

Rob Biedenharn    http://agileconsultingllc.com
Rob@AgileConsultingLLC.com
9f4e11fd04ca1e5a56d00ff3531104ed?d=identicon&s=25 Jean Nibee (jeannibee)
on 2007-07-05 23:12
Rob Biedenharn wrote:
> On Jul 5, 2007, at 3:12 PM, Jean Nibee wrote:
>>
>> Thanks.
>
> I think you've answered your own question, but you might not
> understand why.  The ruby interpreter is "executing" each line within
> the class definition as it is encountered.  If there's no
> PAYMENT_TYPES when the validates_inclusion_of line is reached, it
> really doesn't matter that it *does* appear later in the class
> definition.
>
> -Rob
>
> Rob Biedenharn    http://agileconsultingllc.com
> Rob@AgileConsultingLLC.com

Doh..

Sorry I"m still in 'vm' world w/ my Java code thinking that a Ruby class
is ONLY a definition, I forget to realize it's being interpreted as it's
being read.

Thanks for the wake up.
This topic is locked and can not be replied to.