From 889e9447823a403d28fb8ebc1060c1d614459e46 Mon Sep 17 00:00:00 2001 From: jimtng <2554958+jimtng@users.noreply.github.com> Date: Tue, 10 Oct 2023 00:42:41 +1000 Subject: [PATCH] Refactor ChannelsArray lookup by channel id and uid (#177) --- lib/openhab/core/things/proxy.rb | 2 +- lib/openhab/core/things/thing.rb | 14 +++++++++----- spec/openhab/core/things/thing_spec.rb | 7 +++++++ 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/lib/openhab/core/things/proxy.rb b/lib/openhab/core/things/proxy.rb index 0a37c67a91..82b246e26c 100644 --- a/lib/openhab/core/things/proxy.rb +++ b/lib/openhab/core/things/proxy.rb @@ -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 # diff --git a/lib/openhab/core/things/thing.rb b/lib/openhab/core/things/thing.rb index 556ff6ce9c..ddb0abd4c0 100644 --- a/lib/openhab/core/things/thing.rb +++ b/lib/openhab/core/things/thing.rb @@ -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 diff --git a/spec/openhab/core/things/thing_spec.rb b/spec/openhab/core/things/thing_spec.rb index 4a80ff5240..0c819dfd7e 100644 --- a/spec/openhab/core/things/thing_spec.rb +++ b/spec/openhab/core/things/thing_spec.rb @@ -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