简体   繁体   中英

Ruby - File for Enums

In C# i'm used to create a file called "Enums.cs" and in there define all Enums my app will require... I think it's easier to do it. Now that taking on Ruby, I read and choose the module approach to defining enums because i can associate a int to a "word", like:

module ContractType
  Undefined = 0
  Internship = 1
  CLT = 2
  Contractor = 4
end

Now how can I have my "User" model expose a property like newGuy.CurrentContractType = ContractType.Internship ?!?

Do I import the module? extend ? Or should I reference the GlobalEnums.rb file where all the enums are?

Good question. Simply require the GlobalEnums.rb module at the top of your file and then refer to the module and constant like this:

newGuy.currentContractType = ContractType::Internship

You'll note that in Ruby :: is used to refer to a constant in a namespace (class or module), rather than . . If you have more than one level of nesting, you just chain the :: s:

module Foo
  module Bar
    class Baz
      Qux = "quux"
    end
  end
end

p Foo::Bar::Baz::Qux
# => "quux"

PS I suggest glancing through a Ruby style guide such as this one , in particular the Naming section . With rare exceptions , method and variable names in Ruby are snake_case . Module and class names are CamelCase and other constants are usually SCREAMING_CAMEL_CASE .

With that in mind, a seasoned Rubyist would probably write your code like this:

module MyApp
  module ContractType
    UNDEFINED = 0
    INTERNSHIP = 1
    CLT = 2
    CONTRACTOR = 4
  end
end

# Assuming this is somewhere inside the MyApp namespace...
new_guy.current_contract_type = ContractType::INTERNSHIP

For example, strict conversion methods like Integer(n) and shortcut constructors like URI(str) or Nokogiri::XML(str) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM