Class: Faker::Japanese::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/faker_japanese.rb

Overview

Faker Base class

Direct Known Subclasses

Name

Class Method Summary collapse

Class Method Details

.demodulize(klass) ⇒ String

Convert full class name to the lower case string with class name only

Parameters:

  • klass (Class)

    class name

Returns:

  • (String)


47
48
49
# File 'lib/faker_japanese.rb', line 47

def demodulize(klass)
  klass.to_s.split('::').last.downcase
end

.fetch(key) ⇒ Kanji

Fetch random value from the name dictionary

Parameters:

  • key (String)

    in the @@data

Returns:



77
78
79
80
# File 'lib/faker_japanese.rb', line 77

def fetch(key)
  val = class_variable_get('@@data')[key]
  val[rand(val.size)]
end

.inherited(klass) ⇒ Object

Use callback to store loaded data when subclass is created

Parameters:

  • klass (Class)

    class name



39
40
41
42
# File 'lib/faker_japanese.rb', line 39

def inherited(klass)
  raise("#{klass} should be Class") unless klass.is_a?(Class)
  klass.class_variable_set '@@data', load_data(klass)
end

.load_data(klass) ⇒ Object

Created dictionary with loaded data

Parameters:

  • klass (Module)

    class name



63
64
65
66
67
68
69
70
71
72
# File 'lib/faker_japanese.rb', line 63

def load_data(klass)
  datafile = "#{demodulize(klass)}.yml"
  data = load_raw_yaml(WORKDIR.join('faker_japanese', 'data', datafile))
  return data if data.nil?
  data.inject({}) do |res, item|
    key, values = item
    res.update(key => values.map! { |v| Kanji.new(*v) })
  end
  data
end

.load_raw_yaml(filepath) ⇒ Hash

Load yml file with minor pre-processing

Parameters:

  • filepath (String)

    full path to the file

Returns:

  • (Hash)


54
55
56
57
58
59
# File 'lib/faker_japanese.rb', line 54

def load_raw_yaml(filepath)
  return nil unless filepath && ::File.readable?(filepath)
  YAML.load_file(filepath).each_with_object({}) do |(k, v), h|
    h[k.to_sym] = v
  end
end

.swap_method(klass, name) ⇒ Object

Swap methods if block was evaluated to true

Parameters:

  • klass (Class)

    name of the class

  • name (Symbol)

    method name



85
86
87
88
89
90
# File 'lib/faker_japanese.rb', line 85

def swap_method(klass, name)
  original_method = klass.method(name)
  new_method = method(name)
  proc = proc { yield ? new_method.call : original_method.call }
  klass.singleton_class.send(:define_method, name, proc)
end

.use_japanese_method(klass, name) ⇒ Object

Decide which method to use based on value of Faker::Config.locale

Parameters:

  • klass (Class)

    name of the class

  • name (Symbol)

    method name



95
96
97
# File 'lib/faker_japanese.rb', line 95

def use_japanese_method(klass, name)
  swap_method(klass, name) { Faker::Config.locale == :ja }
end