Module: IseshimaStore::Base

Defined in:
lib/iseshima_store/base.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



11
12
13
14
15
16
17
18
19
# File 'lib/iseshima_store/base.rb', line 11

def self.included(klass)
  klass.extend SingleForwardable
  klass.extend ClassMethods
  klass.def_delegators :scoping, :where, :all, :first, :last, :to_a

  klass.instance_eval do
    attr_accessor :id, :created_at, :description
  end
end

Instance Method Details

#destroyObject



87
88
89
90
# File 'lib/iseshima_store/base.rb', line 87

def destroy
  entity = to_entity
  IseshimaStore::Connection.current.delete(entity)
end

#save!Object



80
81
82
83
84
85
# File 'lib/iseshima_store/base.rb', line 80

def save!
  entity = to_entity
  IseshimaStore::Connection.current.save(entity)
  self.id = entity.key.id
  self
end

#to_entityObject



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/iseshima_store/base.rb', line 92

def to_entity
  entity = Gcloud::Datastore::Entity.new
  entity.key = Gcloud::Datastore::Key.new(self.class.to_s, id)
  unless self.class.properties
    raise StandardError.new("You have to define attr_properties in your model")
  end

  self.class.properties.each do |property|
    property = property.to_s
    value = send(property)
    if value.is_a?(String)
      value = value.force_encoding('UTF-8')
    end
    entity[property] = value
  end
  entity
end