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 lower case string with class name only

Parameters:

  • klass (Class)

    class name

Returns:

  • (String)


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

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

.fetch(key) ⇒ Kanji

Fetch random value from name dictionary

Parameters:

  • key (String)

    in the @@data

Returns:



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

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

.inherited(klass) ⇒ Object

Using callback to store loaded data when subclass is created

Parameters:

  • klass (Class)

    class name



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

def inherited(klass)
  fail("#{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



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

def load_data(klass)
  datafile = File.join(SELFDIR,
                       'faker_japanese',
                       'data', "#{demodulize(klass)}.yml")
  data = load_raw_yaml(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)


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

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 method if block was evaluated to true

Parameters:

  • klass (Class)

    name of the class

  • name (Symbol)

    method name



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

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



96
97
98
99
100
# File 'lib/faker_japanese.rb', line 96

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