1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

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

Posted at

問題

  • 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: ... }

こうなる。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?