Sha256: f806d9f340ff68ec5db61141993e60f670a184ed2c5dcd60abf3f0141b9e085b

Contents?: true

Size: 1.6 KB

Versions: 19

Compression:

Stored size: 1.6 KB

Contents

require 'google/apis/sheets_v4'

class Mapping
  def initialize
    @columns = []
    @primary = nil
  end

  def add_column(name, property: nil, key: nil, getter: nil, setter: nil, hidden: false, primary: false)
    getter_fn = getter if getter
    getter_fn = Proc.new { |obj| obj.send(property) } if property
    getter_fn = Proc.new { |obj| obj[key] } if key
    setter_fn = setter if setter
    setter_fn = Proc.new { |obj, val| obj.send(property + '=') } if property
    setter_fn = Proc.new { |obj, val| obj[key]= val } if key
    @columns.push({
        name: name,
        getter: getter_fn,
        setter: setter_fn,
        hidden: hidden
    })

    if primary
      fail "Only one column can be the primary key" unless @primary.nil?
      @primary = @columns.last
    end
  end

  def to_row(obj)
    @columns.map { |column| column[:accessor].call(obj) }
  end
end

class SheetSyncEngine
  def initialize(mapping, sheet_id: nil)
    @service = Google::Apis::SheetsV4::SheetsService.new
    @sheet_id = sheet_id
    @mapping = mapping
  end

  def credentials=(creds)
    @service.authorization = creds
  end

  def append(items)
    rows = items.map { |item| @mapping.to_row(item) }
    puts rows
  end
end

class Foo
  attr_accessor :prop1
  attr_accessor :prop2

  def initialize(p1, p2)
    @prop1 = p1
    @prop2 = p2
  end
end

mapping = Mapping.new
mapping.add_column('foo', property: :prop1)
mapping.add_column('bar', proc: Proc.new {|o| 'aaa' + o.prop2})
sync = SheetSyncEngine.new(mapping)

items = []
items.push(Foo.new('a', 'b'))
items.push(Foo.new('a1', 'b1'))
items.push(Foo.new('a2', 'b2'))

sync.append(items)

Version data entries

19 entries across 19 versions & 2 rubygems

Version Path
google-api-client-0.10.2 sync.rb
google-api-client-0.10.1 sync.rb
google-api-client-0.10.0 sync.rb
google-api-client-0.9.28 sync.rb
lemboy-google-api-client-0.9.26 sync.rb
google-api-client-0.9.26 sync.rb
google-api-client-0.9.25 sync.rb
google-api-client-0.9.24 sync.rb
google-api-client-0.9.23 sync.rb
google-api-client-0.9.22 sync.rb
google-api-client-0.9.21 sync.rb
google-api-client-0.9.20 sync.rb
google-api-client-0.9.19 sync.rb
google-api-client-0.9.18 sync.rb
google-api-client-0.9.15 sync.rb
google-api-client-0.9.14 sync.rb
google-api-client-0.9.13 sync.rb
google-api-client-0.9.12 sync.rb
google-api-client-0.9.11 sync.rb