Replacing array with a class that acts like array but provides type specific functions? - arrays

I have a class like this:
export class IManor {
tenants: ITenant[];
But I have some aggregate querying funtionality I'd like off of tenants as well and would like to replace it with a class. I know I can attend Array for this but want to be able to access the interface of contents for the aggregate functions, for something like:
class Tenants extends Array<ITenant> {
totalAcres(): number {
let total = 0;
for (const tenant in this) {
total += tenant.acres;
}
return total;
}
}
but the function doesn't appear to be aware of it's interface. My googling turns up generic array extensions only (and the problems with those).
The goal is to be able to to the normal 'let tenant of manor.tenants' while also doing things like manor.tenants.totalAcres();
Any pointers would be appreciated.

Inheritance of you class from Array<ITenant> doesn't affect your previous definition in any way. If you want you methods to be available in IManor class you have to define tenants member as Tenants. In this case you cannot use array syntax for constructing this entity but new Tenants() instead, but all other array method(like filter, map, etc) will be available as well as your methods like totalAcres.
So IManor definition will look like:
export class IManor {
tenants: Tenants = new Tenants();

Related

How to analyze a complex class axiom using OWL API

I read the OWL API documentation, most of the examples are about create class axioms and add them to the ontology. Now, I need to retrieve the restriction of a class, and extract the elements in the restriction.
For example, in the pizza.owl, ChessePizza class is defined by the restriction: "Pizza and (hasTopping some CheeseTopping)". I can use the "getEquivalentClassesAxioms" function to get the whole axiom. But I want to know the details of this axiom, such as the object properties (hasTopping) and classes (CheeseTopping) used in this axiom. Is there any method to extract the elements of a axiom?
The best approach to, for example, extract the property for all existential restrictions, is to write an OWLObjectVisitor.
In a visitor, you implement a visit(OWL... o) for each class that the visitor knows about. For an axiom that defines A equivalentTo p some Q, the visitor would look something like:
OWLObjectVisitor v = new OWLObjectVisitor() {
public void visit(OWLEquivalentClassesAxiom ax) {
// this is an example of recursive visit
ax.classExpressions().forEach(c->c.accept(v));
}
public void visit(OWLObjectSomeValuesFrom ce) {
OWLObjectPropertyExpression p = ce.getProperty();
// here you can do what you need with the property.
}
};
axiom.accept(v);

How to have a generic solution to parse an unknown class to Json in scalaJs

I'm using ScalaJs angular and Upickle and I try to create a filter to transform an unknown class to JSON.
What I tried :
my scope :
var myScope: MyClass = js.native
my filter:
#injectable("copy")
class CopyFilter extends Filter[Any] {
override def filter(any: Any): js.Dynamic = {
val myClass = any.getClass
fromClassToJsValue[myClass](any)
}
}
my function
def fromClassToJsValue[A](value: A)(implicit serializer: Writer[A]): js.Dynamic =
JSON.parse(write(value))
In this case my problem is getClass which returns Class[_] and not MyClass
Is there any solution to find MyClass? (Or maybe any other solution to derive a type Any?)
Broadly speaking, uPickle isn't designed to deal with that; I don't think any of the other JSON serializers are, either. That sort of Any-friendly serialization is usually based on reflection, which mostly isn't available in the JavaScript environment.
I suspect you do need a Filter per case class, albeit probably a one-liner. (Possibly done as a base trait that you mix into the case classes themselves, but I don't know Angular, so I know don't what the constraints look like.)

Swift - Array with specific class type

How can i create array which will hold objects belonging a specific class.
class BaseObject {}
class Derived1: BaseObject {}
class Derived2: BaseObject {}
class Derived2: BaseObject {}
I need to create array in which will hold only Object derived from BaseObject
Something like - var array : [BaseObject.Type] = []
Is there a way to specify this ?
Also, I should be able to use it something like this
if let derived1 = object as? [Derived1] {
}
else if let derived2 = object as? [Derived2] {
}
You can obviously define your array as an array of BaseObject:
var objects: [BaseObject] = [] // or `var objects = [BaseObject]()`
But it's going to let you create a heterogenous collection (of either BaseObject or Derived1 or Derived2 or of any other subclass). That's a core OO design concept (the Liskov substitution principle) that any subclass of BaseObject should (and will) be permitted.
If all you want is to say that you can only have an array of one of the subtypes, you can obviously just define your array as such, e.g.:
var objects: [Derived1] = []
That will obviously allow only Derived1 objects (and any subclasses of Derived1.
90% of the time, the above is sufficient. But in some cases, you might needs some collection with methods that require some inherited base behavior, but for which you don't want to allow heterogenous collections. In this case, I might consider a more protocol-oriented pattern:
Bottom line, should we be subclassing, or should we be using a protocol-oriented approach? I.e. is BaseObject actually something you'll instantiate for its own purposes, or is it there merely to define some common behavior of the subclasses. If the latter, a protocol might be a better pattern, e.g.:
protocol Fooable {
func foo()
}
// if you want, provide some default implementation for `foo` in an
// protocol extension
extension Fooable {
func foo() {
// does something unique to objects that conform to this protocol
}
}
struct Object1: Fooable {}
struct Object2: Fooable {}
struct Object3: Fooable {}
This yields the sort of behavior that you may have been using in your more OO approach, but using protocols. Specifically, you write one foo method that all of the types that conform to this protocol, e.g., Object1, Object2, etc., can use without having to implement foo themselves (unless, of course, you want to because they need special behavior for some reason).
Because this eliminates the subclassing, this then opens the door for the use of generics and protocols that dictate some generalized behavior while dictating the homogenous nature of the members. For example:
struct FooCollection<T: Fooable> {
private var array = [T]()
mutating func append(_ object: T) {
array.append(object)
}
// and let's assume you need some method for your collection that
// performs some `Fooable` task for each instance
func fooAll() {
array.forEach { $0.foo() }
}
}
This is a generic which is a homogenous collection of objects that conform to your protocol. For example, when you go to use it, you'd declare a particular type of Fooable type to use:
var foo = FooCollection<Object1>()
foo.append(Object1()) // permitted
foo.append(Object2()) // not permitted
foo.fooAll()
Now, I only went down this road because in comments elsewhere, you were inquiring about generics. I'd personally only go down this road if the (a) collection really needed to be homogenous; and (b) the collection also wanted to implement some shared logic common to the protocol. Otherwise, I'd probably just stick with a simple [Derived1] (or [Object1]). The above can be powerful when needed, but is overkill for simpler situations.
For more discussion about protocol oriented programming, the homogenous vs heterogenous behavior, traditional stumbling blocks when you're coming from a traditional OO mindset, I'd refer you to the WWDC 2015 video, Protocol-Oriented Programming in Swift, or it's 2016 companion video that builds upon the 2015 video.
Finally, if you have any additional questions, I'd suggest you edit your question providing details on a practical problem that you're trying to solve with this pattern. Discussions in the abstract are often not fruitful. But if you tell us what the actual problem you're trying to solve with the pattern in your question, it will be a far more constructive conversation.

Is it possible to map a table name for a domain object dynamically in grails?

I have a domain that looks something like
class Foo {
String name
static mapping = {
table 'foo'
}
}
but I want to make is more like :
static mapping = {
table "foo_${dynamicVarThatComesFromRequest}"
}
What I want to know is whether this is even possible?
Thanks!
It is possible. You can add a Hibernate interceptor to process all SQL statements and parse/replace some token in the table name you enter in the mapping with the actual table name you want to use.
src/groovy/DynamicTableNameInterceptor.groovy :
import org.hibernate.EmptyInterceptor
public class DynamicTableNameInterceptor extends EmptyInterceptor {
public String onPrepareStatement(String sql) {
// some kind of replacement logic here
def schema=SomeHelperClass.resolveSchema()
return sql.replaceAll('_SCHEMA_', schema)
}
}
grails-app/conf/spring/resources.groovy:
beans = {
// This is for Grails 1.3.x , in previous versions, the bean name is eventTriggeringInterceptor
entityInterceptor(DynamicTableNameInterceptor)
}
I don't think that's possible. Upon application startup, the mapping closure is evaluated and Hibernate mapping are generated as a result. This happens once upon startup, so dynamic resolution will not occur.
Something comparable is done in the multi-tenant-core plugin, using the 'single tenant' setup, you have a seperate database for each tenant.

How to adjust constraints / DB mapping for Map within grails domain class

Following grails domain class:
class MyClass {
Map myMap
}
Now for myMap, grails automatically creates a new table for the elements in the map. However if I add elements which are too long (e.g. 1024 characters), I get a DB error.
Can I somehow tell grails to make the respective column in myMap's table big enough to allow for larger Strings, or do I have to do this manually in the DB?
I already tried
static constraints = {
myMap(maxSize:1024)
}
which doesn't work (as expected because maxSize should refer to the Map's values and not to the Map itself).
If not via constraints, maybe there's a way to do it via
static mapping { ... }
?
An alternative approach I used successfully was to push the map out into a collection of a collaborator domain class.
class DynaProperty {
String name
String value
static belongsTo = MyClass
static constraints = {
value(maxSize:4000) //Or whatever number is appropriate
}
}
And then in MyClass:
class MyClass {
static hasMany = [dynaProperties:DynaProperty]
}
This is almost a map, and it gives you the ability to use dynamic finders to pull up an individual entry.
what are you trying to accomplish? Is there always the same number of things in the map? If there is you should define those properties on your class.
You can see the problem with your current approach -- there is no way to figure out what might be in the map until runtime, so how can grails possibly create a columns for it? Im surprised it even worked to begin with...

Resources