How to specify multiple possible types (type union) for array in MSON? - apiblueprint

I'm struggling a bit to describe what I need exactly but I spent some time browsing the MSON spec and didn't find anything.
This example is a bit contrived but hopefully the intention is clear.
# Animal (object)
This is a base class for all animals. It provides some common structure.
## Properties
... some properties
# Bird (Animal)
## Properties
... some properties
# Fish (Animal)
## Properties
... some properties
# Farm (Object)
## Properties
+ animals (array[Animal], fixed-type)
I want to express that the Farm can contain all kinds of animals but NOT the base class. Is there some way to express that in MSON/JSON Schema so that it validates? Effectively I want to have a choice or type union of Bird and Fish. I don't mind writing out the classes explicitly.
Thanks so much.

Since you're okay writing out the classes explicitly, I think this can be done by writing out what types the array accepts (which all happen to be subclasses of Animal).
+ animals (array[Fish, Bird], fixed-type)

Related

From Java to Ruby: Replacing inheritance by?

I am writing a reader for an embroidery machine file format in Ruby, which has two types of stitches:
Regular stitches: Have a color and relative coordinates.
Jump stitches: Also have a color and relative coordinates, but they are not visible (threads will be removed by hand in the final embroidery and are not visible in any previews that may be generated) and coordinate changes are usually much larger than for regular stitches
In Java, I would probably use an abstract base class "Stitch" and two classes "JumpStitch" and "RegularStitch" inheriting from it. I would then use either quick and dirty instanceof or overloaded methods (handle(JumpStitch stitch), handle(RegularStitch stitch) or something like that) to do something with those (I need the distinction between regular stitches and jump stitches).
How would you achieve something similar in Ruby (as Ruby lacks method overloading and instance_of? being a big nono according to https://stackoverflow.com/a/3893403/3818564)?
Two use cases incorporated from my comments below:
I have a list of all consecutive stitches in a List - some of them are of type RegularStitch, the other ones of type JumpStitch. Now I want to do something with this list.
Say, draw a preview. I am iterating through the list, and decide what to do based on the type of the stitch: RegularStitch will be drawn with the given color, JumpStitch will not be drawn (but the coordinates will be updated from it as they are the basis for the following stitch). – no-trick-pony 22 mins ago
Another example: I want to actually operate an embroidery machine. I can operate the machine faster, when there are only regular stitches (of the same color), but have to slow down the machine if a JumpStitch is next. I hope that clarifies my intentions.
I'd argue your handle(JumpStich) and handle(RegularStitch) are poor uses of OO design in the first place. What's the point of having different types if they don't contain behavior?
Why does this not work?
class Stitch
attr_accessor :color, :coordinates
# ... common behavior
end
class RegularStitch < Stitch
def foo
# regular stitch behavior
end
end
class JumpStitch < Stitch # or RegularStitch?
def foo
# jump stitch behavior
end
end
Your Reader class creates instances depending on the data it reads. We don't know enough about what this foo means, so I can only guess, but this is one of the whole points of polymorphism.

Determining type of an object in ruby

I'll use python as an example of what I'm looking for (you can think of it as pseudocode if you don't know Python):
>>> a = 1
>>> type(a)
<type 'int'>
I know in ruby I can do :
1.9.3p194 :002 > 1.class
=> Fixnum
But is this the proper way to determine the type of the object?
The proper way to determine the "type" of an object, which is a wobbly term in the Ruby world, is to call object.class.
Since classes can inherit from other classes, if you want to determine if an object is "of a particular type" you might call object.is_a?(ClassName) to see if object is of type ClassName or derived from it.
Normally type checking is not done in Ruby, but instead objects are assessed based on their ability to respond to particular methods, commonly called "Duck typing". In other words, if it responds to the methods you want, there's no reason to be particular about the type.
For example, object.is_a?(String) is too rigid since another class might implement methods that convert it into a string, or make it behave identically to how String behaves. object.respond_to?(:to_s) would be a better way to test that the object in question does what you want.
you could also try: instance_of?
p 1.instance_of? Fixnum #=> True
p "1".instance_of? String #=> True
p [1,2].instance_of? Array #=> True
Oftentimes in Ruby, you don't actually care what the object's class is, per se, you just care that it responds to a certain method. This is known as Duck Typing and you'll see it in all sorts of Ruby codebases.
So in many (if not most) cases, its best to use Duck Typing using #respond_to?(method):
object.respond_to?(:to_i)
I would say "yes".
Matz had said something like this in one of his talks,
"Ruby objects have no types."
Not all of it but the part that he is trying to get across to us.
Why would anyone have said
"Everything is an Object" then?
To add he said "Data has Types not objects".
RubyConf 2016 - Opening Keynote by Yukihiro 'Matz' Matsumoto
But Ruby doesn't care as much about the type of object as the class.
We use classes, not types. All data, then, has a class.
12345.class
'my string'.class
Classes may also have ancestors
Object.ancestors
They also have meta classes but I'll save you the details on that.
Once you know the class then you'll be able to lookup what methods you may use for it. That's where the "data type" is needed.
If you really want to get into details the look up...
"The Ruby Object Model"
This is the term used for how Ruby handles objects. It's all internal so you don't really see much of this but it's nice to know. But that's another topic.
Yes! The class is the data type. Objects have classes and data has types. So if you know about data bases then you know there are only a finite set of types.
text blocks
numbers
variable_name.class
Here variable name is "a"
a.class
every variable have a prop with name class. if you print it, it will tell you what type it is. so do like this:
puts a.class

Is it possible to declare types in Ruby?

I am wanting to clarify if it is not possible to declare types in Ruby or is it just not necessary? If someone wanted to declare datatypes would it be possible.
Update: My point in asking is to understand if providing a static type for variables that won't change type will provide a performance increase, in theory.
Some languages as C or Java use “strong” or “static” variable typing. Ruby is a “dynamically typed” language aka "duck typing", which means that variable dynamically changes its own type when type of assigned data has changed.
So, you can't declare variable to some strict type, it will always be dynamic.
What are you trying to do?
You can create your own class:
class Boat
end
If you want an easy way to make a class for holding data, use a struct:
class Boat < Struct.new(:name, :speed)
end
b = Boat.new "Martha", 31
You can NOT declare the class of a variable or method argument, like you can in C. Instead, you can check the type at run time:
b.is_a?(Boat) # Includes subclasses of Boat
b.class == Boat
One proposal to add typing to Ruby is http://bugs.ruby-lang.org/issues/5583 by Yasushi Ando (of parse.y famtour fame). My favorite comment was:
(b) not sure how it can honor duck typing. i think the whole idea is
to (optionally) roast the duck!
If I correctly understood what you mean with type, each Class in Ruby defines a type.
1.class
# => Fixnum
You can create a class to define a custom type
class Book
end
b = Book.new
b.class
# => Book

Ruby and :symbols

I have just started using Ruby and I am reading "Programming Ruby 1.9 - The Pragmatic Programmer's Guide". I came across something called symbols, but as a PHP developer I don't understand what they do and what they are good for.
Can anyone help me out with this?
It's useful to think of symbols in terms of "the thing called." In other words, :banana is referring to "the thing called banana." They're used extensively in Ruby, mostly as Hash (associative array) keys.
They really are similar to strings, but behind the scenes, very different. One key difference is that only one of a particular symbol exists in memory. So if you refer to :banana 10 times in your code, only one instance of :banana is created and they all refer to that one. This also implies they're immutable.
Symbols are similar to string literals in the sense that share the same memory space, but it is important to remark they are not string equivalents.
In Ruby, when you type "this" and "this" you're using two different memory locations; by using symbols you'll use only one name during the program execution. So if you type :this in several places in your program, you'll be using only one.
From Symbol doc:
Symbol objects represent names and some strings inside the Ruby interpreter. They are generated using the :name and :"string" literals syntax, and by the various to_sym methods. The same Symbol object will be created for a given name or string for the duration of a program‘s execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.
So, you basically use it where you want to treat a string as a constant.
For instance, it is very common to use it with the attr_accessor method, to define getter/setter for an attribute.
class Person
attr_accessor :name
end
p = Person.new
p.name= "Oscar"
But this would do the same:
class DontDoThis
attr_accessor( "name" )
end
ddt = DontDoThis.new
ddt.name= "Dont do it"
Think of a Symbol as a either:
A method name that you plan to use later
A constant / enumeration that you want to store and compare against
For example:
s = "FooBar"
length = s.send(:length)
>>> 6
#AboutRuby has a good answer, using the terms "the thing called".
:banana is referring to "the thing
called banana."
He notes that you can refer to :banana many times in the code and its the same object-- even in different scopes or off in some weird library. :banana is the thing called banana, whatever that might mean when you use it.
They are used as
keys to arrays, so you look up :banana you only have one entry. In most languages if these are Strings you run the risk of having multiple Strings in memory with the text "banana" and not having the code detect they are the same
method/proc names. Most people are familiar with how C distinguishes a method from its call with parentheses: my_method vs. my_method(). In Ruby, since parentheses are optional, these both indicate a call to that method. The symbol, however, is convenient to use as a standin for methods (even though there really is no relationship between a symbol and a method).
enums (and other constants). Since they don't change they exhibit many of the properties of these features from other languages.

Does this Ruby code look up identifiers or the values associated with them?

I've been trying to understand this example Ruby code from a blog entry which says it uses the symbols :DEFAULT, :say and :#message "to look up identifiers". But from what I can tell, it's not looking up the identifiers, but the values associated with those identifiers. I thought identifiers are names of variables, methods, etc. So the identifiers would be "DEFAULT", "say" and "message"? The output of the program is below.
Also, why would you need to look up an identifier?
class Demo
# The stuff we'll look up.
DEFAULT = "Hello"
def initialize
#message = DEFAULT
end
def say() #message end
# Use symbols to look up identifiers.
def look_up_with_symbols
[Demo.const_get(:DEFAULT),
method(:say),
instance_variable_get(:#message)]
end
end
dem = Demo.new
puts dem.look_up_with_symbols
When I run the code I get this output:
Hello
#<Method: Demo#say>
Hello
The sample code uses symbols to get at three things: the value of the DEFAULT const (accessed via :DEFAULT), a method object (accessed via :say), and the value of an instance variable (accessed via :#message). None of the three objects were defined using a symbol, yet you can use symbols to access them.
It's a fairly trivial example. The larger point is that symbols can be used to refer to constants, methods, and instance variables, if for some reason you don't want to refer to them directly via their identifiers. I see this most often used in metaprogramming.
Yes, these look up the values of various identifiers.
I'm not sure exactly what you're trying to do, but if you need to translate a symbol (:DEFAULT) to a string ("DEFAULT") use to_s (:DEFAULT.to__s). If you want to look up all the possible identifiers it would depend on what you're looking for.
myobject.methods # show a list of instance methods an object has (like "say" above)
myobject.instance_variables # show a list of instance variables an object has (like "#message" above)
myobject.class.constants # show a list of class level constants (like "DEFAULT" above)
I get the most mileage out of these methods when debugging or trying out new APIs. The only reason I'd probably use these in production code is to output some kind of automatic string representation (XML,HTML,CSV) of an object.

Resources