Swift Declare Class Func in Protocol

You can review Apple’s Documentation (subsection Method Requirements). There says: As with type property requirements, you always prefix type method requirements with the static keyword when they are defined in a protocol. This is true even though type method requirements are prefixed with the class or static keyword when implemented by a class In practice, … Read more

How to dynamically define a class method which will refer to a local variable outside?

Class methods don’t really exist in Ruby, they are just singleton methods of the class object. Singleton methods don’t really exist, either, they are just ordinary instance methods of the object’s singleton class. Since you already know how to define instance methods (using Module#define_method), you already know everything you need to know. You just need … Read more

ActiveRecord Rails 3 scope vs class method

There was more of a difference in Rails 2.x, since named_scopes did not execute your queries (so you could chain them), whereas class methods generally did execute the queries (so you could not chain them), unless you manually wrapped your query in a scoped(…) call. In Rails 3, everything returns an ActiveRecord::Relation until you need … Read more

How to understand the difference between class_eval() and instance_eval()?

As the documentation says, class_eval evaluates the string or block in the context of the Module or Class. So the following pieces of code are equivalent: class String def lowercase self.downcase end end String.class_eval do def lowercase self.downcase end end In each case, the String class has been reopened and a new method defined. That … Read more

__getattr__ for static/class variables

__getattr__() and __str__() for an object are found on its class, so if you want to customize those things for a class, you need the class-of-a-class. A metaclass. class FooType(type): def _foo_func(cls): return ‘foo!’ def _bar_func(cls): return ‘bar!’ def __getattr__(cls, key): if key == ‘Foo’: return cls._foo_func() elif key == ‘Bar’: return cls._bar_func() raise AttributeError(key) … Read more

Attaching a decorator to all functions within a class

The cleanest way to do this, or to do other modifications to a class definition, is to define a metaclass. Alternatively, just apply your decorator at the end of the class definition using inspect: import inspect class Something: def foo(self): pass for name, fn in inspect.getmembers(Something, inspect.isfunction): setattr(Something, name, decorator(fn)) In practice of course you’ll … Read more

Should constructors comply with the Liskov Substitution Principle? [closed]

No, when you use a constructor you know you are dealing with the subtype. This allows you to have preconditions not required for the parent constructor such as other parameters. This is why in most languages the constructor name is that of the class being created. A good example of how this is that a … Read more