Module: Genderize::ClassMethods

Defined in:
lib/genderize.rb

Instance Method Summary collapse

Instance Method Details

#genderize(col_name = "gender") ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/genderize.rb', line 17

def genderize(col_name = "gender")
  # Reads the DB column value for gender attribute and creates a new Gender
  # object with it's value
  #
  # The object is memoized for future calls.
  #
  # Returns a Gender
  define_method col_name do
    current_value = instance_variable_get("@#{col_name}")
    persist_value = Genderize::Gender.new(read_attribute(col_name))
    return current_value || instance_variable_set("@#{col_name}", persist_value)
  end

  # Writes to the DB column the new value for the gender attribute
  # Sets the instance varaible value too
  #
  # string - A String indicating the gender. Must be either 'm', "M", 'f' or "F".
  #
  # Raises ArgumentError if gender is not a single alphanumeric character "m" or "f"
  define_method "#{col_name}=" do |string|
    string = string.to_s.first
    unless string.to_s =~ /\A(m|f|)\Z/i
      raise ArgumentError, "Gender must be one of '', 'm', or 'f'"
    end
    write_attribute(col_name, string)

    if string.blank?
      instance_variable_set("@#{col_name}", string)
    else
      instance_variable_set("@#{col_name}", Genderize::Gender.new(read_attribute(col_name)))
    end
  end

end