[Ironruby-core] overriding indexers

Ivan Porto Carrero ivan at flanders.co.nz
Sun Jan 3 10:08:31 EST 2010


Hi

A while ago there were the methods __getitem__ and __setitem__ which allowed
to override an indexer.
I can't find these methods anymore and I also can't find a way to override
an indexer.

namespace ClrModels {

    public class IndexerContained{

        private Dictionary<string, string> _inner = new Dictionary<string,
string>{
            { "key1", "value1" },
            { "key2", "value2" },
            { "key3", "value3" },
            { "key4", "value4" }
        };

        public virtual string this[string name]{
          get { return _inner[name]; }
          set { _inner[name] = value; }
        }
    }

    public class IndexerCaller{

        public string CallIndexOnClass(IndexerContained klass, string name){
            return klass[name];
        }

        public string CallIndexOnInterface(IHaveAnIndexer klass, string
name){
            return klass[name];
        }

    }
}

class MySubIndexer < ClrModels::IndexerContained;
   def [](name); 6; end;
   def Item(name); 7; end;
   def item(name); 8; end;
   def get_Item(name); 9; end;
end

>> cons = ClrModels::IndexerCaller.new
=> ClrModels.IndexerCaller
>> cons.call_index_on_class(MySubIndexer.new, "key")
unknown:0: warning: do not use Fixnums as Symbols
=> 'Fail'


And a spec to go with it:

require File.dirname(__FILE__) + "/../spec_helper"

describe "CLR to CLR interactions" do

  describe "when isolating CLR classes" do

    describe "that have an indexer" do
      before do
        @cons = ClrModels::IndexerCaller.new
        @ind = Caricature::Isolation.for(ClrModels::IndexerContained)
      end

      it "should work without expectations" do
        @cons.call_index_on_class(@ind, "key1").should.be.nil
      end

      it "should work with an expectation" do
        @ind.when_receiving(:__getitem__).return("5")

        @cons.call_index_on_class(@ind, "key1").should.equal "5"
      end


    end

  end

end
---
Met vriendelijke groeten - Best regards - Salutations
Ivan Porto Carrero
Blog: http://flanders.co.nz
Google Wave: portocarrero.ivan at googlewave.com
Twitter: http://twitter.com/casualjim
Author of IronRuby in Action (http://manning.com/carrero)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/ironruby-core/attachments/20100103/26c22f54/attachment-0001.html>


More information about the Ironruby-core mailing list