Class: I3Ipc::Reply

Inherits:
Object
  • Object
show all
Defined in:
lib/i3ipc/reply.rb

Overview

Wrapper for reply from i3-ipc.

Able to parse Numeric, String, TrueClass, FalseClass, Array, Hash from passed string in json format.

Examples:

response = Reply.parse(
 %Q{
    {
     "name": "LVDS1",
     "active": true,
     "current_workspace": "4",
     "rect": {
      "x": 0,
      "y": 0,
      "width": 1280,
      "height": 800
     }
    }
  }
)

p response.name        # => "LVDS1"
p response.active      # => true
p response.rect.width  # => 1280
# ...

response = Reply.parse(%Q{ {"data": [{"key1": true}, {"key2": false}]} })
p response.data[0].key1 # => true
p response.data[0].key2 # => false

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ Reply

Returns a new instance of Reply.



35
36
37
# File 'lib/i3ipc/reply.rb', line 35

def initialize(data)
  @data = data.dup
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object



57
58
59
60
61
62
63
64
# File 'lib/i3ipc/reply.rb', line 57

def method_missing(name, *args, &block)
  if @data.include?(name)
    raise ArgumentError.new('wrong number of arguments (%d for 0)' % args.length) if args.length > 0
    return @data[name]
  else
    super
  end
end

Class Method Details

.parse(response) ⇒ Reply

Parses response from I3-ipc protocol.

Parameters:

  • response (String)

    response from i3 in json format.

Returns:

  • (Reply)

    object with dynamically accessed values.



44
45
46
# File 'lib/i3ipc/reply.rb', line 44

def self.parse(response)
  parse_data JSON.parse(response)
end

Instance Method Details

#respond_to?(method_sym, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


66
67
68
69
70
71
72
# File 'lib/i3ipc/reply.rb', line 66

def respond_to?(method_sym, include_private = false)
  if @data.include?(method_sym)
    true
  else
    super
  end
end

#success?Boolean

Indicates whether this reply is successful or not.

Returns:

  • (Boolean)

    false if this reply represents and error from i3-ipc protocol. Otherwise returns true, which means that request is successful and reply has some data.



53
54
55
# File 'lib/i3ipc/reply.rb', line 53

def success?
  not self.respond_to? :error
end

#to_hObject



78
79
80
81
82
83
# File 'lib/i3ipc/reply.rb', line 78

def to_h
  data = @data.dup
  data.each do |k, v|
    data[k] = Reply.unparse_data v
  end
end

#to_sObject



74
75
76
# File 'lib/i3ipc/reply.rb', line 74

def to_s
  JSON.pretty_generate(to_h)
end