1 Replies - 1034 Views - Last Post: 19 December 2016 - 06:44 PM Rate Topic: -----

#1 CTphpnwb  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 3714
  • Posts: 13,468
  • Joined: 08-August 08

Ruby inheritance issue?

Posted 19 December 2016 - 05:12 PM

class Isbnvalidator < ActiveModel::Validator

	def validate(record)
		Rails.logger.debug "debugging.......#{record.isbn}"
		@err = 'The number must have 10 or 13 digits.';
		Rails.logger.debug "error: #{@err}"
		validLengths = [10, 13]
		checkMissing = [9, 12]
		Rails.logger.debug "record.isbn.length: #{record.isbn.length}"

		if validLengths.include?(record.isbn.length)
			myclass = "ISBN" + record.isbn.length.to_s
			Rails.logger.debug "My class = #{myclass}"
			obj = Object.const_get(myclass).new
			Rails.logger.debug "\n-=-=-=-=-=-= calling initialize...\n\n"
			obj.initialize
			Rails.logger.debug "\n*******isValidISBN called...\n\n"
			return obj.isValidISBN(record.isbn)
		end
		Rails.logger.debug "\n+++++++++++++isValidISBN NOT called...\n\n"

		return false

	end

end

class ISBNbase
	def isValidISBN(num)
		@mult = 1
		val = 0
		temp = num.upcase
		len = num.length - 1

		initialize()

		# Sum the digits * the multiplier value.
		for n in 0..len
			if temp[n] = "X"
				val = val + 10 * mult
			else
				val = val + num[n] * mult
			end
				# The mulitplier varies depending on the position in the number and the number of digits.
			multiplier()
		end

		# Modulo varies by the number of digits.
		(val % @modulo)

	end
end

class ISBN10 < ISBNbase
	def initialize
		@mult = 1
		@modulo = 11
	end

	def multiplier
		@mult = @mult + 1
	end

end

class ISBN13 < ISBNbase

	def initialize
		@mult = 1
		@modulo = 10
	end

	def multiplier
		@mult = (@mult + 2) % 4
	end

end


The error:

Quote

private method `initialize' called for #<ISBN10:0x007fa2aa838070 @mult=1, @modulo=11>

Why is initialize private?

Is This A Good Question/Topic? 0
  • +

Replies To: Ruby inheritance issue?

#2 dorknexus  Icon User is offline

  • or something bad...real bad.
  • member icon

Reputation: 1272
  • View blog
  • Posts: 4,625
  • Joined: 02-May 04

Re: Ruby inheritance issue?

Posted 19 December 2016 - 06:44 PM

Initialize is private by design. Since your base class does not define #initialize, it inherits it from BasicObject, which is private.

If you want to use your init code elsewhere you could move it into its own method and then invoke it from #initialize, and anywhere else you want to reset the state.

It's probably better to make ISBNBase a mixin instead of a base class in this case in my opinion.

This post has been edited by dorknexus: 19 December 2016 - 06:49 PM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1