When i try to compile the render-object method shown here in the documentation http://restas.lisper.ru/en/manual/special-pages.html,
(defmethod restas:render-object ((designer mydrawer)
(code (eql hunchentoot:+http-internal-server-error+)))
(setf (hunchentoot:content-type*) "text/plain")
"Oh, all very bad")
it gives
There is no class named RESTAURANT::MYDRAWER SIMPLE-ERROR
How do these render-object thingies work ?
render-object is a generic function that takes a rendering object, which is either the object passed to :render-method for define-route or the value of *default-render-method*, and the object to render. It then renders that object (usually as text, although you could probably render it to an octet array as well).
The example assumes that you have a class called mydrawer. To get this working you would need to do something like the following:
(defclass mydrawer () ())
(defmethod restas:render-object ((designer mydrawer)
(code (eql hunchentoot:+http-internal-server-error+)))
(setf (hunchentoot:content-type*) "text/plain")
"Oh, all very bad")
(defmethod restas:render-object ((designer mydrawer) obj)
;; Default rendering of objects goes here,
;; this will just call the default render method
(restas:render-object nil obj))
And then use an instance of mydrawer as the render method either for individual routes, or for a restas module.
Related
as my post describes it, I'd like to create an UTIL class with a never_both function.
class
UTIL
create
default_create
feature -- could be in class BOOLEAN
double_implies, reversible_implies, never_both (a, b: BOOLEAN): BOOLEAN
-- Into boolean class with never_with
do
if a and b then
Result := False
else
Result := True
end
end
end
When I use it
invariant
never_both: {UTIL}.never_both (attached last_error, attached last_success_message)
the compiler complains about a VUNO error
never_both used in the non-object call is not a class feature.
I saw 2 notations about objects creating
- {UTIL}.never_both (a, b)
- ({UTIL}).never_both (a, b)
Whats the difference between them?
How to create an application wide (could be even world wide once if you want!) object for the use of this UTIL if possible in Eiffel?!
I know this is a TUPLE of questions so I put them in Bold
If you want to use a feature without creating the corresponding object, it should be marked as a class feature. This is done in the feature postcondition with the same keyword:
foo ...
do
...
ensure
instance_free: class
...
end
After that, the feature can be used in an objectless call {BAR}.foo ....
The notation ({BAR}).qux does not denote an objectless call. It is an object call on the target object of type TYPE [BAR]. The object describes the type BAR.
I am new to Groovy.
I have a function in which I am writing a value to map.
def addTraceEntry(key, value) {
def traceability = [:]
traceability[key] = value.trim()
println "This print happens in function addTraceEntry " + traceability
}
I have another function that needs to verify whether the above function works properly.
def testAddTraceEntry() {
def key = 'test_key'
def value = 'test_value'
addTraceEntry(key, value)
println "This print happens in function testAddTraceEntry " + traceability
assert value == traceability[key]
}
I am invoking the testAddTraceEntry() function using the function name:
testAddTraceEntry()
When I run this, I get the ERROR:
This print happens in function addTraceEntry [test_key:test_value]
Caught: groovy.lang.MissingPropertyException: No such property: traceability for class: HelloWorld
groovy.lang.MissingPropertyException: No such property: traceability for class: HelloWorld
at HelloWorld.testAddTraceEntry(HelloWorld.groovy:53)
at HelloWorld.run(HelloWorld.groovy:57)
In the function testAddTraceEntry it clearly does not know the value of traceability so seems like its giving an ERROR for that.
I tried to return the value of traceability.
def addTraceEntry(key, value) {
def traceability = [:]
traceability[key] = value.trim()
println "This print happens in function addTraceEntry " + traceability
return traceability
}
But this yields the same ERROR.
There are a bunch of things worth mentioning after seeing the code you have wrote.
First thing - the scope of variables and encapsulation. Let's throw away technicalities for a moment and focus on something even more important. In method addTraceEntry you persist some state, which is fine. However, the implementation of the method testAddTraceEntry reveals that this method tries to know way to much about the implementation details of addTraceEntry. It encapsulates (hides in other words) persistence logic (from the API point of view you, as a caller, don't know that it persists key and a value inside the map) and that is why testAddTraceEntry should never ever make assumptions that calling this method mutated some structure. If you do so, then:
your test method contracts side effects and not the expected business logic (storing data in some kind of global map - don't do it. Ever)
your test blocks any evolution of tested method implementation - imagine, that you decided to store key and value in a different structure. You may do it without breaking any API contract (your function produces the same results), but the test method will fail and you will have to modify it.
Second thing - your addTraceEntry method always produces a map with a single entry. It doesn't make much sense and if you call your function let's say 4 times you will end up with 4 maps where each one of them contain a single key mapped to a single value.
There are at least various ways to improve implementation of your methods. The simplest thing you can do is to implement a class that encapsulates logic for storing keys and values. Consider following example:
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap
class TraceEntriesStorage {
private final ConcurrentMap<String, Object> entries = [:] as ConcurrentHashMap
def addTraceEntry(String key, Object value) {
entries.put(key, value)
}
def containsTraceEntry(String key) {
return entries.containsKey(key)
}
def retrieveTraceEntryForKey(String key) {
return entries.get(key)
}
}
This is a simple class with 3 short methods. It stores trace entries inside the internal concurrent map (to solve problems with concurrent access). Now, your test method could look like this:
def storage = new TraceEntriesStorage()
storage.addTraceEntry("test_key", "test_value")
assert storage.containsTraceEntry("test_key")
assert storage.retrieveTraceEntryForKey("test_key") == "test_value"
You create an instance of this class, you add an entry and you check if methods containsTraceEntry and retrieveTraceEntryForKey return expected values. As you can see it doesn't matter where we stored this trace entry - it matters that the class we have implemented behaves as expected. To make this test method even better you could add an assertion that checks if there is no trace entry for test_key before we actually insert it - this way we know that adding trace entry change internal state of the class. But what is nice in this approach is that as long as we don't break the contract, we can experiment and modify implementation of TraceEntriesStorage. Because what is most important - adding trace entries have to allow to retrieve them back from the object. How it gets stored, where it gets stored - it doesn't matter.
I hope you find this answer useful and it will help you in learning Groovy and designing a better programs. Happy hacking!
You need to combine adding the return statement to addTraceEntry() with assigning the returned value to a variable in testAddTraceEntry():
def traceability = addTraceEntry(key, value)
from the doc: Important gotcha on spying real objects!
List list = new LinkedList();
List spy = spy(list);
//Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
when(spy.get(0)).thenReturn("foo");
//You have to use doReturn() for stubbing
doReturn("foo").when(spy).get(0);
so, when does when thenReturn not working on spy?
same question here
I'm hoping to use the Coinbase Bitcoin Exchange node.js API from inside ClojureScript.
The goal is to replicate the first javascript example on the page:
var CoinbaseExchange = require('coinbase-exchange');
var publicClient = new CoinbaseExchange.PublicClient();
But in my following code I've started by trying to access PublicClient at all:
(ns plutus.core
(:require
[cljs.nodejs :as nodejs]))
(def coinb (nodejs/require "coinbase-exchange"))
(nodejs/enable-util-print!)
(defn -main [& args]
(def pc (js/PublicClient.)))
(println pc))
(set! *main-cli-fn* -main)
This throws a ReferenceError: PublicClient is not defined, though I've also tried (along with similar variations):
(def pc (. coinb (PublicClient)))
(def pc (.PublicClient coinb))
(def pc (:PublicClient coinb))
All of which have failed by printing nil. I've pretty closely studied this article for any relevant examples, but I'm confused on how using node.js affects the naming of things, if at all.
Really its not a naming issue, its more about how to use new with nested properties in an object. Unfortunately, you can't get a reference to PublicClient and then new that after the fact.
(new (.-PublicClient coinb))
It does not work even though (.-PublicClient coinb) returns a function.
You need to point to the location of the function, by using it's dot notation within ClojureScript:
(new coinb.PublicClient)
;; OR, more idiomatic
(coinb.PublicClient.)
That should give you what you want.
Anybody else seeing this?
> ((.-getProducts (cb.PublicClient.)) (fn [_ _ _] nil))
#object[TypeError TypeError: self.makeRelativeURI is not a function]
I've set up a "psuedo-oop" system inside of my script that lets me better interact with the UserData from my application. My system works remarkably good except that it doesn't pass references, it passes values. Because of this, if I say something like:
World.Body.Parent=World.Body2
Nothing actually happens because it never actually sets the Bodys parent to the other body. Instead, it kind of simplifies to this:
World=World.Body2
(Because World is the parent of the Body so it is returned). Now, if I do something like this, on the other hand:
print(World.Body.Parent.Type)
==> World
Because it correctly got the World object (being the parent of the Body).
Now with this all in mind, is there some way to make sure it is passed more by reference instead of actually sending the object? Any ideas would be appreciated!
Here is the relevant source code that I'm using:
local target=_G
function AddService(service)
Blank=(function(...) return end)
CreateTemporaryIndex=(function(obj)
local env_meta={
__index=(function(this, key)
if obj[key]~=nil and obj[key]~=key then
if type(obj[key]) ~= "userdata" then
return obj[key]
else
local r,i=pcall(function() Blank(obj[key].Type) end)
if r then
return CreateTemporaryIndex(obj[key])
else
return (function(...) local arg={...} table.remove(arg,1) return obj[key](obj,unpack(arg)) end)
end
end
else
local ofObj=obj:Child(key)
if ofObj~=nil then
return CreateTemporaryIndex(ofObj)
end
end
return nil
end)
}
local nRe={}
setmetatable(nRe,env_meta)
return nRe
end)
target[service.Name]=CreateTemporaryIndex(service)
end
AddService(__Environment.World)
AddService(__Environment.Players)
AddService(__Environment.Lighting)
AddService(__Environment.Environment)
The __index metamethod is only called when accessing properties. In order to implement a custom setter you will need to define the __newindex metamethod as well. You can find more info in the section of the Lua manual that I linked to.
That said, if I were you I would think again whether all of this proxy table complication is really needed. For an example of one of the little corner cases that you might have not covered, iterating over your environments with pairs and ipairs will fail unless you add __ipairs and __pairs metamethods as well.