0
Help us understand the problem. What are the problem?

posted at

Firestoreでcollectionのfield名をcamelCaseとsnake_caseで交互に置換したい

問題

  • Javascriptは通常camelCaseで書く
  • Rubyは通常snake_caseで書く

そうするとFirestoreのcollectionのfieldはcamelCaseだけど、rubyにデータがある時はsnake_caseにしたい。

解決

Railsとしてここに置く

config/initializers/firestore.rb
module FirestoreOliveBranch
  module Outgoing
    def create(data)
      d = data.deep_transform_keys { |key| key.to_s.camelcase(:lower) }
      super d
    end

    def set(data, merge: nil)
      d = data.deep_transform_keys { |key| key.to_s.camelcase(:lower) }
      super d, merge: merge
    end
  end

  module Incoming
    def data
      super.deep_transform_keys { |key| key.to_s.underscore.to_sym }
    end
  end
end

module Google
  module Cloud
    module Firestore
      class DocumentReference
        prepend FirestoreOliveBranch::Outgoing
      end
    end
  end
end

module Google
  module Cloud
    module Firestore
      class DocumentSnapshot
        prepend FirestoreOliveBranch::Incoming
      end
    end
  end
end

こうする事でfirestoreに書き込む際

{ created_at: ... }

{ createdAt: ... }

こうなり、これのdoc.get.data

{ created_at: ... }

こうなる。

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
0
Help us understand the problem. What are the problem?