How to Use ActiveResource with Shallow Nested Routes? - rest

I have a Rails application that has a Company resource with a nested resource Employee. I'm using shallow routing, so to manipulate Employee, my routes are:
GET /employees/1
PUT /employees/1
DELETE /employees/1
POST /companies/1/employees
How can I create, read, update, and destroy Employees using ActiveResource?
To create employees, I can use:
class Employee < ActiveResource::Base
self.site = "http://example.com/companies/:company_id"
end
But if I try to do:
e=Employee.find(1, :params => {:company_id => 1})
I get a 404 because the route /companies/:company_id/employees/:id is not defined when shallow routes are used.
To read, edit, and delete employees, I can use:
class Employee < ActiveResource::Base
self.site = "http://example.com"
end
But then there doesn't seem to be a way to create new Employees, due to the lack of the companies outer route.
One solution would be to define separate CompanyEmployee and Employee classes, but this seems overly complex.
How can I use a single Employee class in ActiveResource to perform all four CRUD operations?

I'm using Rails 3.0.9. You can set the prefix like this:
class Employee < ActiveResource::Base
self.prefix = "/companies/:company_id/"
end
And then
Employee.find(:all, :params => {:company_id => 99})
or
e = Employee.new(:name => "Corey")
e.prefix_options[:company_id] = 1
It will replace :company_id with the value from prefix_options.

There is a protected instance method named collection_path that you could override.
class Employee < ActiveResource::Base
self.site = "http://example.com"
def collection_path(options = nil)
"/companies/#{prefix_options[:company_id]}/#{self.class.collection_name}"
end
end
You would then be able to this to create employees.
e = Employee.new(:name => "Corey")
e.prefix_options[:company_id] = 1
e.save
It doesn't seem like the prefix_options is documented other than in the clone method so this might change in future releases.

See this article: http://blog.flame.org/2009/11/04/activeresource-and-shallow-nested-routes.html
Here, the author proposes to override class method collection_path. This makes sense, since this method is used also by new_element_path and will retrieve the same path in both cases.
Example:
class Employee < ActiveResource::Base
self.site = "http://example.com"
def self.collection_path(prefix_options = {},query_options=nil)
super
"/companies/#{query_options[:company_id]}/#{collection_name}.#{format.extension}#{query_string(query_options)}"
end
end
Then you can find employees for a company by doing:
company = Company.find(:first)
Employee.find(:all, :params => {:company_id => company.id })

I found it best to override ActiveResource::Base.element_path with the same functionality as defined in the library, but omitting the use of prefix_options in the returned value. There is no
class Employee < ActiveResource::Base
self.site = 'http://example.com'
self.prefix = '/companies/:company_id/'
# Over-ride method and omit `#{prefix(prefix_options)}` from the returned string
def self.element_path(id, prefix_options = {}, query_options = nil)
"/#{collection_name}/#{URI.parser.escape id.to_s}.#{format.extension}"
end
end
The Employee class will then behave as usual, with no need to assign prefix_options to the instance as suggested in other solutions.

Related

Structuring Lua classes

I'm constructing a class in Lua that has a number of groups of related functions within it, but am unsure whether there's a better way to structure it. I currently have to develop for a Lua 5.1 environment but am hopeful that Lua 5.3 will be possible in the near future.
The class will be used in a number of different Lua programs, so I want something I can just drop in as a single chunk of code (the environment I'm programming for means that modules and require aren't and won't be an option).
Ideally I want a black box piece of code (except for the exposed public methods) and not to duplicate code in different classes (to improve maintainability).
What I have at present is (generalised):
function Fclass()
--here I declare a bunch of local functions that can be called by any of the public methods
local function A(parms)
end
--Public methods set 1
--here I declare a bunch of state variables shared by BSelector and GetB
local BSelector = function()
A(parmvalues)
--returns a bunch of iup controls with supporting (complicated) logic
end
local GetB = function()
--returns the values of the iup controls created in Bselector
end
--Public methods set 2
--here I declare a bunch of state variables shared by DSelector and GetD
local DSelector = function()
--returns a bunch of iup controls with supporting (complicated) logic
end
local GetD = function()
A(parmvalues)
--returns the value of the iup controls created in Dselector
end
return{BSelector =BSelector , GetB =GetB, DSelector =DSelector , GetD =GetD}
end
The "B" and "D" groups of methods are totally independent except they both use the local functions "A" etc. (which don't depend on external variables); their state variables ideally should be local to the group.
Is this a sensible structure? Or should I be splitting the "B" and "D" groups into two separate classes and either duplicating the local functions or dropping them in as a separate piece of code? I don't really want to expose the local functions outside the classe(es) because there will inevitably be naming conflicts... Most programs will use all the groups of methods, although there will be some that only use a single group.
Or is there a better way to do this?
I'm invoking them thus:
myB = Fclass()
myD = Fclass()
someresults = myB.Bselector()
otherresults = myD.Dselector()
Updated to add: I'm advised I may not be using the terminology properly and what I'm doing isn't classes. My approach is based on Programming in Lua and was selected because I wanted to keep the state variables for the class? object? private -- not accessible except via the public methods.
In your example, it seems you encapsulate the state of your instances through closures, not table values.
While this has the advantage of stronger encapsulation, as upvalues are invisible from the outside without using the debug library, it also comes with the disadvantage that Lua has to close each method for each instance, wasting some more memory (not a lot though).
Another benefit is that when instance variables are implemented as table fields, they need not be declared before the method, as table indexing is string-based, whereas when implemented as closures, the local varaible needs to be known before the function is defined (this also applies to other methods, which in either implementation work the same way as instance variables).
It's more common to store instance variables as table values inside the object, and passing the object as a first argument to the functions. There's even syntactic sugar for this.
There's lots of ways for doing classes in Lua, with many different tradeoffs (some are better at inheritance, while others perform better, etc.)
Since you don't seem to need any inheritance, you can go with a simple factory function, as you're pretty much doing already.
The way I personally like to build such factory functions is:
local object do
local class = {}
local meta = {__index=class} -- Object metatable
function class:print() -- A method of the class
print("Hello, I am an object and my x is " .. tostring(self.x))
end
function object(self) -- The factory function for the Class
self.x = self.x or 0
return setmetatable(self, meta)
end
end
local o = object {
x = 20
}
o:print()
o.x = 30
o:print()
This has the benefit that, for classes with many methods and many instances, the methods aren't copied into every instance, which saves some memory.
Alternatively, you can do something like this
local object do
local function object_print(self)
print("Hello, I am an object and my x is " .. tostring(self.x))
end
function object(self)
self.x = self.x or 0
self.print = object_print -- Store method directly in the object
return self
end
end
Again, this saves a reference to every method in every instance, wasting some memory. The benefit is that you can now think of classes as traits. When you write
person { name = "henry" }
You can think of it as creating a new person with the name Henry, but you can also think of it as creating an object with the name Henry and adding the person trait to it.
Because of this benefit of combining two concepts of OOP into one implementation and not having any pesky inheritance, it's my favourite way of building objects in Lua in most simple cases.
Update
The trait approach also lends itself to defining several classes/traits together:
local person, human do
-- Some generic method shared by both classes
local function object_get_name(self)
return self.name
end
-- Person uses this as a method, but human uses
-- it as a function through an upvalue. Both work,
-- but have different upsides and downsides.
-- A method of person
local function person_say_hi(self)
print(self:get_name() .. " says hi!")
-- Calling get_name as a method here
end
-- A method of human
local function human_describe(self)
print(object_get_name(self) .. ' is a human!')
-- Calling get_name as an upvalue
end
function person(self)
self.name = self.name or 'A person'
self.say_hi = person_say_hi
self.get_name = object_get_name
-- Needs to be a method because person_say_hi assumes it to be one
return self
end
function human(self)
self.name = self.name or 'A human'
self.describe = human_describe
return self
end
end
-- Create a new person
local henry = person{ name = "Henry" }
henry:say_hi()
-- Create a new human
local steve = human { name = "Steve" }
steve:describe()
-- Change the way henry gets his name
function henry:get_name()
return self.name:upper()
end
-- This only affects henry; all other "person" objects keep their old
henry:say_hi()
-- This only works because say_hi accesses the method
-- Add the person trait to steve
person(steve)
steve:describe() -- Steve is still a human
steve:say_hi() -- Steve is also a person now
Some years ago I built myself a superclass for basic OOP functionality in Lua.
Usage:
Person = LuaObject:extend({
__name = "Person",
name = "",
age = 0,
})
-- constructor
function Person:new(name, age)
Person.__super.new(self)-- calling the super constructor
self.name = name
self.age = age
end
function Person:getName()
return self.name
end
function Person:getAge()
return self.age
end
Feel free to use it:
--[[
LuaObject for basic OOP in Lua
Lua 5.0
]]
local function newIndexFunction(tbl, name, value)
if name == "new" and type(value) == "function" then
local constructor = value
rawset(tbl, name, function(self, ...)
local object = self
if object.__class == nil then
object = {}
object.__class = self
object.__id = string.sub(tostring(object), 8)
self.__index = self
setmetatable(object, self)
end
constructor(object, unpack(arg))-- Lua 5.0
-- constructor(object, ...)-- Lua 5.1+
return object
end)
else
rawset(tbl, name, value)
end
end
local function toStringFunction(tbl)
return tbl:toString()
end
LuaObject = {__name = "LuaObject"}
setmetatable(LuaObject, {__newindex = newIndexFunction, __tostring = toStringFunction})
function LuaObject:extend(class)
class = class or {}
self.__index = self
self.__newindex = newIndexFunction
self.__tostring = toStringFunction
local constructor = nil
if class.new ~= nil then
constructor = class.new
class.new = nil
end
setmetatable(class, self)
if constructor ~= nil then
class.new = constructor
end
class.__super = self
return class
end
function LuaObject:new()
end
function LuaObject:getSuperClass()
return self.__super
end
function LuaObject:getClass()
return self.__class
end
function LuaObject:toString()
return string.format("[%s] %s", self.__class.__name, self.__id)
end
function LuaObject:isInstance(value)
return value ~= nil and type(value) == "table" and getmetatable(value) == self
end
--[[
-- examples
-- basic class
Person = LuaObject:extend({
__name = "Person",
name = "",
age = 0,
})
-- constructor
function Person:new(name, age)
Person.__super.new(self)-- calling the super constructor
self.name = name
self.age = age
end
function Person:getName()
return self.name
end
function Person:getAge()
return self.age
end
-- extending classes
Customer = Person:extend({
__name = "Customer",
id = 0,
})
function Customer:new(id, name, age)
Customer.__super.new(self, name, age)
self.id = id
end
function Customer:getID()
return self.id
end
-- overriding methods
function Customer:getName()
-- calling super methods
local realResult = Customer.__super.getName(self)
if string.len(realResult) <= 5 then
return realResult
else
return string.sub(realResult, 1, 5)
end
end
-- testing
local customer1 = Customer:new(1, "rollback", 19)
local customer2 = Customer:new(2, "Kori", -1)
print(assert(customer1:getName() == "rollb", "Overriding of getName failed"))
print(assert(customer2:getName() == "Kori", "Overriding of getName failed"))
print(assert(customer1:getID() == 1, "Error in getID"))
print(assert(customer1:getAge() == 19, "Error in getAge"))
print(customer1)
]]
You can create 2 up-values for your class functions. the 1st value holds public variables that will be accessed by your class' caller, such as the functions themselves and any caller handled options.
while the 2nd will be for your private values those that are only known and accessible from within the class. You can use this private table to store internal state or other inner workings that will not be exposed to the caller.
function class(first, second)
local public = {first}
local _private = {second}
function _private.A(parms)
--private function not available outside of class.
end
function public:selector() -- public class available to caller
_private.A(parmvalues) -- calls private class
end
function public:get()
return _private[1]
end
return public
end
myB = class('hello', ' world!') --passing in a variable for public, and one for private.
myD = class('hello...', ' world?')
print(myB[1] .. myB:get()) --get a public value, and uses get function to retrieve private value
print(myD[1] .. myD:get())
Additionally if the class functions should never be changed by your user, you can enforce that by changing return public to:
local meta = {
__index = public,
__newindex = function(t, k, v)
error("this table is read-only")
end,
__metatable = false
}
return setmetatable({}, meta) -- this make the public table read only

Exclude derived entities from requests to the base class

I have this DbContext:
public class DataContext : DbContext
{
public DbSet<Base> Bases {get;set}
public DbSet<Sub> Subs {get;set}
}
Sub is a subclass of Base.
When I'm querying the list of Base entities like so:
Context.Bases.ToListAsync()
It returns me every entities, either Base or Sub.
How can I configure my model context to get only the entities that are of Base type and not the ones that derives from it.
The best (or least worst) solution I found is to directly use the shadow property:
Context.Bases.Where(b => EF.Property<string>(b, "Discriminator") == "Base")).ToListAsync();
It works but needs to be repeted now and then, each time I need to query Bases. I'd have prefered a solution in the OnModelCreating method.
I'll accept this answer unless someone else find a better solution.
You'd have to use OfType<T>:
var basesOnly = await _context.Bases.OfType<Base>().ToListAsync();
UPDATE
Sorry, then. I could have sworn the above works, but it doesn't. The next best method I can think of is to simply filter out the types you don't want. It's not ideal, because it requires specifying all subtypes in your query, which then means you need to remember to update it if you add more subtypes.
var basesOnly = await _context.Bases.Where(x => !(x is Sub)).ToListAsync();
How can I configure my model context to get only the entities that are
of Base type and not the ones that derives from it.
You cannot. Every Sub is a Base. So querying all Bases includes all Subs. Eg code like the following must succeed:
Base b = db.Bases.Where(i => i.Id == 1).Single();
if (b is Sub)
begin
Sub s = (Sub)b;
. . .
end
else //other Sub
begin
Sub2 s = (Sub2)b;
. . .
end
You can fetch an anonymous type with the just the base class properties.
And asking this question suggests that inheritance might is not the right modeling technique for your scenario.
If what you want it to fetch the Entities of type Base, but not the subtype Sub, then you can do that with a query like:
var q = from b in db.Bases
where !(b is Sub)
select b;
Which translates to :
SELECT [b].[Id], [b].[Discriminator], [b].[Name], [b].[Size]
FROM [Bases] AS [b]
WHERE [b].[Discriminator] IN (N'Sub', N'Base')
AND NOT ([b].[Discriminator] = N'Sub')
But you can't (currently) exclude all subtypes without enumerating them. Eg this query:
var q2 = from b in db.Bases
where b.GetType() == typeof(Base)
select b;
Will not be completely translated to SQL, and will filter out the subtypes on the client.

Detecting direct instantiation with nDepend

With the nDepend API, would something like the following be possible?
I want to keep a watch out for instances where our object factory has been bypassed and a concrete class is being instantiated directly.
Obviously I'd need to be able to filter out things like:
StringBuilder stringBuilder = new StringBuilder();
perhaps by adding to the Where clause type names to exclude, or namespaces in which to check, but I want to make sure we see:
IMyCustomType item = ObjectFactory.Get<IMyCustomType>();
and not this:
MyCustomType item = new MyCustomType();
Thanks.
Maybe such code rule below could help you, hopefully it is understandable enough to not have to comment it:
warnif count > 0
let ctors = Application.Namespaces.WithNameLike("Namespaces1*").ChildMethods().Where(m => m.IsConstructor)
let codeThatMustNotCallCtors = Application.Namespaces.WithNameLike("Namespaces2*").ChildMethods()
from m in codeThatMustNotCallCtors.UsingAny(ctors)
select new { m, ctorsCalled = m.MethodsCalled.Intersect(ctors ) }

How to generate an unique ID for an class instance in Scala?

I have a class that needs to write to a file to interface with some legacy C++ application.
Since it will be instantiated several times in a concurrent manner,
it is a good idea to give the file an unique name.
I could use System.currentTimemili or hashcode, but there exists the possibility of collisions.
Another solution is to put a var field inside a companion object.
As an example, the code below shows one such class with the last solution, but I am not sure it is the best way to do it (at least it seems thread-safe):
case class Test(id:Int, data: Seq[Double]) {
//several methods writing files...
}
object Test {
var counter = 0
def new_Test(data: Seq[Double]) = {
counter += 1
new Test(counter, data)
}
}
Did you try this :
def uuid = java.util.UUID.randomUUID.toString
See UUID javadoc, and also How unique is UUID? for a discussion of uniqueness guarantee.
it is a good idea to give the file an unique name
Since all you want is a file, not id, the best solution is to create a file with unique name, not a class with unique id.
You could use File.createTempFile:
val uniqFile = File.createTempFile("myFile", ".txt", "/home/user/my_dir")
Vladimir Matveev mentioned that there is a better solution in Java 7 and later - Paths.createTempFile:
val uniqPath = Paths.createTempFile(Paths.get("/home/user/my_dir"), "myFile", ".txt"),

EF1: Filtering derived types of entity class using .OfType<> by passing a string value

I have a situation where I'm trying to filter a LINQ select using a derived sub class.
ctx.BaseEntity.OfType<SubClass>() - this works fine.
However I'd like to do this using a string value instead. I've come across a performance barrier when I have lots (>20) Sub Classes and selecting an Entity without using OfType just isn't an option. I have a generic UI that renders from the base class, so I don't know what Class Type will be returned at compile time.
So what I'd like to do is this:
Perform a projected Select where I
return just the SubClassType from
the database
Perform a second select
using this value as the OfType to
only select the relevant related
entity from the database (No mass
unions generated)
int id = 1;
var classType = (from c in ctx.BaseClass.Include("ClassType")
where c.id == id
select new
{
c.ClassType.TypeName
}).First();
BaseClass caseQuery = ctx.BaseClass.OfType<classType.TypeName>()
.Include("ClassType")
.Include("ChildEntity1")
.Include("ChildEntity2")
.Where(x => x.id== id);
But obviously this won't work because OfType requires a Type and not a string.
Any ideas on how I can achieve this?
Update:
As a side note to the original question, it turns out that the moment you project a query that uses a Navigation Property - it builds the monster SQL too, so I've ended up using a stored procedure to populate my ClassType entity from the BaseClass Id.
So I've just got it to work using eSQL, which I'd never used before. I've posted the code here just in case it helps someone. Has anyone else got a more strongly typed solution they can think of?
BaseClass caseQuery = ctx.BaseClass.CreateQuery<BaseClass>("SELECT VALUE c FROM OFTYPE(Entities.[BaseClass],namespace.[" + classType.TypeName + "]) as c")
.Include("ClassType")
.Include("ChildEntity1")
.Include("ChildEntity2")
.Where(x => x.id== id).FirstOrDefault();
To answer the headline question about calling OfType with a string / runtime type, you can do the following:
// Get the type, assuming the derived type is defined in the same assembly
// as the base class and you have the type name as a string
var typeToFilter = typeof(BaseClass)
.Assembly
.GetType("Namespace." + derivedTypeName);
// The use reflection to get the OfType method and call it directly
MethodInfo ofType = typeof(Queryable).GetMethod("OfType");
MethodInfo ofTypeGeneric = method.MakeGenericMethod(new Type[] { typeToFilter });
var result = (IQueryable<Equipment>)generic.Invoke(null, new object[] { equipment });
Combine this with your stored procedure to get the class name and you (should?) avoid the massive join - I don't have table-per-type implementation to play with so I can't test.