Skip to content

caryl/simple_enum

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SimpleEnum

Description

Simple Enum is a simple and useful plugin for using enum attribute.

  • version 0.2.4

  • by Caryl

Requirements

  • Rails 3.1 or greater

Installation

gem 'simple_enums'

Getting Started

Example:

class User
    include SimpleEnum
    has_enum :status, :enums => [[:unactived, 0, "未激活"],[:normal, 1, "正常"],[:locked, 2, "已锁定"]], \
      :column => :status_id, :default => :normal
end

options:

has_enum name, enums[, column][, default]
  • name: enum name

  • enum: a array to define enums, each enum defined by [key(symbol), value(integer), human_name(string)]

  • column: optional, must be a column, attr_accessor or a getter and setter method pair

    • default is name + ‘_id’

  • default: enum’s default value, can assigned by a symbol(key) integer(value) or string(human name)

    • default is the first enum

Usage

This will define the following methods dynamically:

class methods:

  • User.status_enums => [[:unactived, 0, “未激活”],[:normal, 1, “正常”],[:locked, 2, “已锁定”]]

  • User.options_for_status => [[“正常”, 1], [“草稿”, 0], [“锁定回复”, 2], [“隐藏”, 3]]

  • User.status_name(:normal) => “正常” #return enum’s human name

    • params: array, symbol, integer, string or array

  • User.status_value(:normal) => 1 #return enum value

    • params: array, symbol, integer, string or array

  • User.new => #default value has been set: user.status == 1

  • User.status_is(:normal) => same as User.status_in(:normal)

instance methods:

  • user.status => #same as status_id

  • user.status= => #same as status_id =

  • user.status_key => :locked #enum key

  • user.status_name => ‘正常’ #enum’s human name

  • user.status_is?(:normal) => true

    • params: array, symbol, integer, string or array

  • user.status_default_value => #default value , assign by :default option, default is the first of :enums

  • user.set_status_value(:locked) #set value, same as user.status=2 or user.status_id=2

    • params: array, symbol, integer, string or array

  • user.update_status_value(:locked) #update value

    • params: array, symbol, integer, string or array

named scope

  • User.status_in(:locked)

    • params: array, symbol, integer, string or array

About

a enum plugin

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages