From e832b18cf00043c8f3af875dea766342f82f8038 Mon Sep 17 00:00:00 2001 From: mesmerize Date: Wed, 29 Sep 2021 20:15:31 +0200 Subject: [PATCH] singleton --- lib/product.rb | 5 +++++ lib/products_controller.rb | 17 +++++++++++++++++ spec/anything_spec.rb | 4 ++++ 3 files changed, 26 insertions(+) create mode 100644 lib/product.rb create mode 100644 lib/products_controller.rb diff --git a/lib/product.rb b/lib/product.rb new file mode 100644 index 0000000..56e8c1c --- /dev/null +++ b/lib/product.rb @@ -0,0 +1,5 @@ +class Product + def initialize(type) + @type = type + end +end diff --git a/lib/products_controller.rb b/lib/products_controller.rb new file mode 100644 index 0000000..8841094 --- /dev/null +++ b/lib/products_controller.rb @@ -0,0 +1,17 @@ +class ProductsController + # include Singleton - right way to do that + + @instance = new + + private_class_method :new + + attr_accessor :product + + def self.instance + @instance + end + + def show + @product = PRODUCT + end +end diff --git a/spec/anything_spec.rb b/spec/anything_spec.rb index e39e005..d792474 100644 --- a/spec/anything_spec.rb +++ b/spec/anything_spec.rb @@ -8,11 +8,15 @@ describe ProductsController do it 'cannot be instantiated via :new' do + expect{ ProductsController.new }.to raise_error NoMethodError end it 'can be instantiated only once' do + expect(ProductsController.instance.object_id).to eq(ProductsController.instance.object_id) end it 'does some work' do + ProductsController.instance.show + expect(ProductsController.instance.product).to be(PRODUCT) end end