Inline C output value store on rails controller - ruby-on-rails

I am using inline C to get some output. What I am trying to do is execute the inline C code and render its output to rails view via controller.
The code snippet for inline C is:
class Something
inline(:C) do |builder|
builder.c 'int test1() {
char array[20] = "-------Hello from Ruby!------\n";
printf("%s", array);
return array;
}'
end
end
Object is created in the controller of the rails application this way.
def index
something = Something.new
#something = something.test1
end
Now, when I try to store output value of the inline C, it just is not applicable while the output is displayed on the rails log(not on the log file). I am sure that the value displayed is via return array; of the Something class.
The index method has #something instance set which just stores some value like 4421355280 , but not the value. ie "-------Hello from Ruby!------"
I have an index to render the corresponding controller action.
<h1>Travel</h1>
<h3><%= #something %></h3>
How can I possibly store output value "-------Hello from Ruby!------" into #something?
Output of inline C
Thanks in advance.

Sorry guys, its seems that I had some problem on return type on C code. It should have been:
class Something
inline(:C) do |builder|
builder.c 'char * test1() {
char array[20] = "-------Hello from Ruby!------\n";
printf("%s", array);
return array;
}'
end
end

Related

Building a map for parallel step from directory names [duplicate]

For example, the groovy File class has a nice iterator that will filter out just directories and not files:
void eachDir(Closure closure)
When I use eachDir, I have to use the verbose method of creating the collection first and appending to it:
def collection = []
dir1.eachDir { dir ->
collection << dir
}
Any way to get it back to the nice compact collect syntax?
I don't know of any "idiomatic" way of doing this, nice riddle! =D
You can try passing the eachDir, or any similar function, to a function that will collect its iterations:
def collectIterations(fn) {
def col = []
fn {
col << it
}
col
}
And now you can use it as:
def dir = new File('/path/to/some/dir')
def subDirs = collectIterations(dir.&eachDir)
def file = new File('/path/to/some/file')
def lines = collectIterations(file.&eachLine)
(that last example is equivalent to file.readLines())
And only for bonus points, you may define this function as a method in the Closure class:
Closure.metaClass.collectIterations = {->
def col = []
delegate.call {
col << it
}
col
}
def dir = new File('/path/to/some/dir')
def subDirs = dir.&eachDir.collectIterations()
def file = new File('/path/to/some/file')
def lines = file.&eachLine.collectIterations()
Update: On the other hand, you might also do:
def col = []
someDir.eachDir col.&add
Which I think is quite less convoluted, but it's not leveraging the collect method as you requested :)
Not for the specific example that you're talking about. File.eachDir is sort of a weird implementation IMO. It would have been nice if they implemented iterator() on File so that you could use the normal iterator methods on them rather than the custom built ones that just execute a closure.
The easiest way to get a clean one liner that does what you're looking for is to use listFiles instead combined with findAll:
dir1.listFiles().findAll { it.directory }
If you look at the implementation of eachDir, you'll see that it's doing this (and a whole lot more that you don't care about for this instance) under the covers.
For many similar situations, inject is the method that you'd be looking for to have a starting value that you change as you iterate through a collection:
def sum = [1, 2, 3, 4, 5].inject(0) { total, elem -> total + elem }
assert 15 == sum

Grails : Split string in GSP view

I know how to split the string within a Controller or Domain class.
But i want to split the string inside the GSP.
My string will look like:
ASD25785-T
I want to be able to split this into 2 strings inside the GSP view.
String a = ASD25785
String b = T
Is it possible to do that inside the GSP?
How about something like this:
<%
String[] tokens = "ASD25785-T".split("-")
String b = tokens[0]
String c = tokens[1]
%>
NB. use try catch because you may get ArrayOutofBoundException
It depends if you have a predefind format or you want something generic.
Without try/catch and using the regex find method in String:
<%
String s="ASD25785-T"
String a,b
s.find(/(.+)-(.+)/) { fullMatch, first, second -> [
a=first
b=second
}
%>
If you are certain that there will always be a match, then it is a cute one-liner:
<%
String s="ASD25785-T"
def (a,b) = s.find(/(.+)-(.+)/) { fullMatch, first, second -> [first,second]}
%>
Source:
http://naleid.com/blog/2009/04/07/groovy-161-released-with-new-find-and-findall-regexp-methods-on-string
NB: However, if you want to use it in your view, you should create a tag. Grails taglibs are almost trivial to write, and much better to use in GSP code.
http://grails.github.io/grails-doc/2.4.x/ref/Command%20Line/create-tag-lib.html
http://grails.github.io/grails-doc/latest/guide/single.html#taglibs
Here's a string manipulation taglib
class StringsTaglib {
def split = { attrs, body ->
String input= attrs.input
String regex= attrs.regex
int position= attrs.index as Integer
out << input.split(regex)[position]
}
}
you could then use it like this:
a:<g:split input="ASD25785-T" regex="-" index="0"/>
b:<g:split input="ASD25785-T" regex="-" index="1"/>

Grails returning value from controller to gsp

I have been searching on how to return an integer value from controller to the gsp. I tried using this:
def test(){
def val = 1;
return val;
}
but it does not work. Please help.
Try
def test(){
def val = 1;
[val:val]
}
Add this code to your controller:
def test(){
def v = 10
render view:'test.gsp', model:[v:v]
}
Then, access the value from your test.gsp by "${v}"
Note that the render view is optional for test.gsp, i've written it only for demo purpose.. (i.e change the gsp filename).
Hope it helps.
The return statement is used to return values from services to controllers.
If you want to pass values from the controller to gsp, use:
[variableNameInGSP : valueToBeReturned]

how do i iterate the tables parameters which is present under the main table?

In lua ,im calling a function which returns a table variable that contains many parameter internally..but when i get that value i couldnt access the paramter which is present in the table. I can see the tables parameter in the original function in the form of
[[table:0x0989]]
{
[[table:0x23456]]
str = "hello"
width = 180
},
[[table:0x23489]]
{
str1 = "world"
}
it shows like this.but when it returns once i can able to get the top address of table like [[table:0x0989]]..when i tried acessing the tables which is present inside the main table.it is showing a nil value...how do i call that ?? can anyone help me??
If I'm reading it correctly you're doing this:
function my_function ()
--do something
return ({a=1, b=2, c=3})
end
From that you should be able to do this:
my_table = my_function()
then
print(my_table.a) --=> 1
print(my_table.b) --=> 2
print(my_table.c) --=> 3

Grails GSP render problem

I've got a domain class which I want to, at run time, do a database call to populate a list of objects as a property. I have a tree with a 'headMember' property and that property is an object which has the following function:
def marriages = {
def marriages = Marriage.findAll("from Marriage as m where m.mainMember.name=:name", [name:name])
return [marriages:marriages]
}
in my GSP, I use ${tree?.headMember?.marriages} to access the 'headMember' property of the model which is passed to the view 'tree' from the following function in the relevant controller:
def show = {
def tree = Tree.get(params.id)
render(view:'show', model:[tree:tree])
}
when I view this in my browser, i get:
Member$_closure1#3708ab98
where I'd expect a list.
Any ideas what I'm doing wrong?
Cheers.
When you call marriages, you are calling a closure and this closure is returned. I think that you should rework it to be a method, something like that:
static transients = ['marriages'] // tell hibernate that marriages is not a persistent property
List<Marriages> getMarriages(){
return Marriage.findAll("from Marriage as m where m.mainMember.name=:name", [name:name])
}
This way, when you call ${tree?.headMember?.marriages} in your GSP, the getMarriages() method is called and list of marriages should be returned.

Resources