Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/simple/sql/helpers.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
module ::Simple::SQL::Helpers
end

require_relative "./json.rb"
require_relative "helpers/decoder.rb"
require_relative "helpers/encoder.rb"
require_relative "helpers/row_converter.rb"
Expand Down
4 changes: 2 additions & 2 deletions lib/simple/sql/helpers/decoder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ def decode_value(type, s)
when :"timestamp without time zone" then ::Time.parse(s)
when :"timestamp with time zone" then ::Time.parse(s)
when :hstore then HStore.parse(s)
when :json then ::JSON.parse(s)
when :jsonb then ::JSON.parse(s)
when :json then ::Simple::SQL::JSON.parse(s)
when :jsonb then ::Simple::SQL::JSON.parse(s)
when :boolean then s == "t"
else
# unknown value, we just return the string here.
Expand Down
37 changes: 37 additions & 0 deletions lib/simple/sql/json.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# rubocop:disable Style/DoubleNegation

# This class implements lazy JSON parsing. When enabled it should improve
# performance if data is fetched from the database in a JSON format, and is
# consumed via a JSON encoder.
#
# This seems a bit far-fetched, but that use case is actually quite common
# when implementing a JSON API.
class Simple::SQL::JSON < BasicObject
def self.parse(str)
new(str)
end

def initialize(json_string)
@json_string = json_string
end

def method_missing(sym, *args, &block)
parsed.send(sym, *args, &block) || super
end

def respond_to_missing?(name, include_private = false)
parsed.send(:respond_to_missing?, name, include_private) || super
end

def parsed
@parsed ||= ::JSON.parse(@json_string)
end

def ==(other)
super || (parsed == other)
end

def to_json(*_args)
@json_string
end
end