Skip to content

Commit

Permalink
Refactor ChannelsArray lookup by channel id and uid (#177)
Browse files Browse the repository at this point in the history
  • Loading branch information
jimtng authored Oct 9, 2023
1 parent 50ffa16 commit 889e944
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 6 deletions.
2 changes: 1 addition & 1 deletion lib/openhab/core/things/proxy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class Proxy < Delegator
#
# @return [Array] channels
def channels
Thing::ChannelsArray.new(super.to_a)
Thing::ChannelsArray.new(self, super.to_a)
end

#
Expand Down
14 changes: 9 additions & 5 deletions lib/openhab/core/things/thing.rb
Original file line number Diff line number Diff line change
Expand Up @@ -64,13 +64,17 @@ module Thing
# Array wrapper class to allow searching a list of channels
# by channel id
class ChannelsArray < Array
def initialize(thing, array)
super(array)
@thing = thing
end

# Allows indexing by both integer as an array or channel id acting like a hash.
# @param [Integer, String] index Numeric index or string channel id to search for.
# @param [Integer, String, ChannelUID] index
# Numeric index, string channel id, or a {ChannelUID} to search for.
def [](index)
if index.respond_to?(:to_str)
key = index.to_str
return find { |channel| channel.uid.id == key }
end
return @thing.get_channel(index) if index.is_a?(ChannelUID)
return @thing.get_channel(index.to_str) if index.respond_to?(:to_str)

super
end
Expand Down
7 changes: 7 additions & 0 deletions spec/openhab/core/things/thing_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,13 @@
it "returns its thing" do
expect(thing.channels["phase#name"].thing).to be thing
end

it "supports lookup by channel UID" do
channel_id = "phase#name"
channel_uid = org.openhab.core.thing.ChannelUID.new(thing.uid, channel_id)
expect(thing.channels[channel_uid]).not_to be_nil
expect(thing.channels[channel_uid]).to be thing.channels[channel_id]
end
end
end

Expand Down

0 comments on commit 889e944

Please sign in to comment.