spot7.org logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories

compose objects without initializing objects that are not in hash


Your question raises some interesting issues. I will try to explain how you can fix it, but, as @Uri mentions, there may be better ways to address your problem.

I've assumed @tranfee is to be set equal to the first value in the hash whose key begins with "tran" and that @rate is to be set equal to the first value in the hash whose key begins with "rate". If that interpretation is not correct, please let me know.

Note that I've put initialize in the PaymentType module in a class (Papa) and made TranFee and Rate subclasses. That's the only way you can use super within initialize in the subclasses of that class.

Code

class Transaction
  attr_reader :tranfee, :rate

  def initialize(hash={})
    o = PaymentType::TranFee.new(hash)
    @tranfee =
o.instance_variable_get(o.instance_variables.first)
    o = PaymentType::Rate.new(hash)
    @rate =
o.instance_variable_get(o.instance_variables.first)
  end
end

.

module PaymentType
  class Papa
    def initialize(hash, prefix)
      key, value = hash.find { |key,value|
key.start_with?(prefix) && value }
      (raise ArgumentError, "No key beginning with
#{prefix}") unless key
      instance_variable_set("@#{key}", value)
      self.class.singleton_class.class_eval {
attr_reader key }
    end
  end

  class TranFee < Papa
    def initialize(hash)
      super hash, "tran"
    end
  end

  class Rate < Papa
    def initialize(hash)
      super hash, "rate"
    end
  end    
end

I believe the method Object#singleton_class has been available since Ruby 1.9.3.

Example

reg_debit = {"name" => "reg_debit",
"rate_base" => 0.0005, "tran_fee" => 0.21,
             "rate_basis_points" => 0.002,
"tran_auth_fee" => 0.10}

a = Transaction.new reg_debit
p Transaction.instance_methods(false) #=>
[:tranfee, :rate]
p a.instance_variables                #=>
[:@tranfee, :@rate]
p a.tranfee                           #=> 0.21
p a.rate                              #=>
0.0005

Categories : Ruby

Related to : compose objects without initializing objects that are not in hash
How to compose mutable objects const correctly
The easy approach to const correctness: Use transitive const. It seems you are asking for a little too much for free at the language level. It's actually designed (among other things) so that you pay for what you use, and to be safe and performant. And yes, it can be very verbose. As far as containers which are physically-const-aware, C++ is certainly capable of supporting the distinction; e.g.:

Categories : C++
(Java) How can I sort an array of objects, and break ties between two objects?
You need to modify Comparable to not only consider wins, but to consider ties, especially when wins occur. So in your compareTo, add an if to check when wins are equal, and then inside that if do the check on losses. Here you can even add in the check for draws as well.

Categories : Java
Creating an Array with class objects and with derived Objects C++
First, you need to fix a syntax error: unlike Java or C# where array type is indicated by a pair of empty square brackets after the type name, C++ "understands" square brackets after the name of the variable change the type of the variable to an array type. Die[] regDieBag[10]; // ^^ This syntax is incorrect Now, when you see these lines together Die regDieBag[10]; // ^ No asterisk and reg

Categories : C++
How can I delete the objects in Amazon s3 after the objects reaches certain number say 20
You need to bring the check for size > 20 outside your loop. Also, maximum number of summaries that can be pulled at a time is 1000 - so, you need to check if there are more, pull them and delete them. AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); AmazonS3 s3 = new AmazonS3Client(credentials); String bucketName = "testbucket"; System.out.println("Listing objects")

Categories : Java
CSV objects in Ruby. What are they exactly?
map works on any object that includes the Enumerable mixin. In order to work with Enumerable, the class needs to provide each - that's the foundation all the other nice methods are built on. Objects of the CSV class fit this pattern, as you can see in the documentation for the class. (The reason it doesn't push it straight into an array is because it's nice to be able to read the input file line

Categories : Ruby
Recently Add
ruby self in an instance methods in a module
Problems with rspec scope in before blocks
Querying a specific cell with known column and row
Parsing through nested hash using .present? - undefined method `[]' for nil:NilClass (NoMethodError)
"params" doesn't work in Ruby (Sinatra framework)
Specifying a Puppet + Ruby version matrix in CircleCI
How to upload a file using RestClient in Ruby?
Shibboleth authentication in Rails
Random, intermittent "argument out of range" error while parsing CSV and parsing time
Ruby: Wrong number of Arguments for a subclass changes number of arguments
amalgamate two ruby arrays
Geocoder request.location returns nil
Access most recent table row and its data
how to search multiple word in the same file using ruby and the get the output which contains those words
MongoDB search query for stats
rake command parsing options after --
Ruby: cannot load such file - LoadError
Understanding attributes in AWS DynamoDB with Ruby
Ruby: Get last character from user input
Undefined method 'delegate' for capybara::dsl::module
neo4j ruby wrapper create or update
'on raise' hook in ruby
Ruby OCI8 - bind optional parameters to Oracle Stored procedure
How to install the app only once for the suite
Different test unit output in Rubymine and console
Can Rake run each test in a separate Ruby instance?
Ruby strftime in UK format i.e. dd/mm/yy
Accessing hash in Ruby like objects in Coffeescript
How do I correct my script, that it doesn't matter what file name has the .xml that is uploaded?
Ruby: Tests not runing
© Copyright 2017 spot7.org Publishing Limited. All rights reserved.