Search Results

Search found 175 results on 7 pages for 'metaprogramming'.

Page 2/7 | < Previous Page | 1 2 3 4 5 6 7  | Next Page >

  • What to read as a good intro and quickstart to aspect-oriented programming and metaprogramming?

    - by Ivan
    As I've found myself repeating myself a lot, writing very similar queries and classes for different entities (despite of doing strong object and relational normalisation), etc, I've came to an Idea that I could and should automate the most of this and write an engine which will compile simple declarative models I specify into all the code limiting my job to describe the task and and finally just customise the result as needed. As far as I know this is about metaprogramming and aspect-oriented programming. How do I get acquainted with modern tools available quickly so that I don't invent one more bicycle developing my own?

    Read the article

  • How do I write an RSpec test to unit-test this interesting metaprogramming code?

    - by Kyle Kaitan
    Here's some simple code that, for each argument specified, will add specific get/set methods named after that argument. If you write attr_option :foo, :bar, then you will see #foo/foo= and #bar/bar= instance methods on Config: module Configurator class Config def initialize() @options = {} end def self.attr_option(*args) args.each do |a| if not self.method_defined?(a) define_method "#{a}" do @options[:"#{a}"] ||= {} end define_method "#{a}=" do |v| @options[:"#{a}"] = v end else throw Exception.new("already have attr_option for #{a}") end end end end end So far, so good. I want to write some RSpec tests to verify this code is actually doing what it's supposed to. But there's a problem! If I invoke attr_option :foo in one of the test methods, that method is now forever defined in Config. So a subsequent test will fail when it shouldn't, because foo is already defined: it "should support a specified option" do c = Configurator::Config c.attr_option :foo # ... end it "should support multiple options" do c = Configurator::Config c.attr_option :foo, :bar, :baz # Error! :foo already defined # by a previous test. # ... end Is there a way I can give each test an anonymous "clone" of the Config class which is independent of the others?

    Read the article

  • Rails Metaprogramming: How to add instance methods at runtime?

    - by Larry K
    I'm defining my own AR class in Rails that will include dynamically created instance methods for user fields 0-9. The user fields are not stored in the db directly, they'll be serialized together since they'll be used infrequently. Is the following the best way to do this? Alternatives? Where should the start up code for adding the methods be called from? class Info < ActiveRecord::Base end # called from an init file to add the instance methods parts = [] (0..9).each do |i| parts.push "def user_field_#{i}" # def user_field_0 parts.push "get_user_fields && @user_fields[#{i}]" parts.push "end" end Info.class_eval parts.join

    Read the article

  • How do I use Ruby metaprogramming to refactor this common code?

    - by James Wenton
    I inherited a project with a lot of badly-written Rake tasks that I need to clean up a bit. Because the Rakefiles are enormous and often prone to bizarre nonsensical dependencies, I'm simplifying and isolating things a bit by refactoring everything to classes. Specifically, that pattern is the following: namespace :foobar do desc "Frozz the foobar." task :frozzify do unless Rake.application.lookup('_frozzify') require 'tasks/foobar' Foobar.new.frozzify end Rake.application['_frozzify'].invoke end # Above pattern repeats many times. end # Several namespaces, each with tasks that follow this pattern. In tasks/foobar.rb, I have something that looks like this: class Foobar def frozzify() # The real work happens here. end # ... Other tasks also in the :foobar namespace. end For me, this is great, because it allows me to separate the task dependencies from each other and to move them to another location entirely, and I've been able to drastically simplify things and isolate the dependencies. The Rakefile doesn't hit a require until you actually try to run a task. Previously this was causing serious issues because you couldn't even list the tasks without it blowing up. My problem is that I'm repeating this idiom very frequently. Notice the following patterns: For every namespace :xyz_abc, there is a corresponding class in tasks/... in the file tasks/[namespace].rb, with a class name that looks like XyzAbc. For every task in a particular namespace, there is an identically named method in the associated namespace class. For example, if namespace :foo_bar has a task :apples, you would expect to see def apples() ... inside the FooBar class, which itself is in tasks/foo_bar.rb. Every task :t defines a "meta-task" _t (that is, the task name prefixed with an underscore) which is used to do the actual work. I still want to be able to specify a desc-description for the tasks I define, and that will be different for each task. And, of course, I have a small number of tasks that don't follow the above pattern at all, so I'll be specifying those manually in my Rakefile. I'm sure that this can be refactored in some way so that I don't have to keep repeating the same idiom over and over, but I lack the experience to see how it could be done. Can someone give me an assist?

    Read the article

  • How can one make a 'passthru' function in C++ using macros or metaprogramming?

    - by Ryan
    So I have a series of global functions, say: foo_f1(int a, int b, char *c); foo_f2(int a); foo_f3(char *a); I want to make a C++ wrapper around these, something like: MyFoo::f1(int a, int b, char* c); MyFoo::f2(int a); MyFoo::f3(char* a); There's about 40 functions like this, 35 of them I just want to pass through to the global function, the other 5 I want to do something different with. Ideally the implementation of MyFoo.cpp would be something like: PASSTHRU( f1, (int a, int b, char *c) ); PASSTHRU( f2, (int a) ); MyFoo::f3(char *a) { //do my own thing here } But I'm having trouble figuring out an elegant way to make the above PASSTHRU macro. What I really need is something like the mythical X getArgs() below: MyFoo::f1(int a, int b, char *c) { X args = getArgs(); args++; //skip past implicit this.. ::f1(args); //pass args to global function } But short of dropping into assembly I can't find a good implementation of getArgs().

    Read the article

  • How do you extend a Ruby module with macro-like metaprogramming methods?

    - by Ian Terrell
    Consider the following extension (the pattern popularized by several Rails plugins over the years): module Extension def self.included(recipient) recipient.extend ClassMethods recipient.class_eval { include InstanceMethods } end module ClassMethods def macro_method puts "Called macro_method within #{self.name}" end end module InstanceMethods def instance_method puts "Called instance_method within #{self.object_id}" end end end If you wished to expose this to every class, you can do the following: Object.send :include, Extension Now you can define any class and use the macro method: class FooClass macro_method end #=> Called macro_method within FooClass And instances can use the instance methods: FooClass.new.instance_method #=> Called instance_method within 2148182320 But even though Module.is_a?(Object), you cannot use the macro method in a module: module FooModule macro_method end #=> undefined local variable or method `macro_method' for FooModule:Module (NameError) This is true even if you explicitly include the original Extension into Module with Module.send(:include, Extension). How do you add macro like methods to Ruby modules?

    Read the article

  • How do I efficiently code both the client and server at the same time?

    - by liamzebedee
    I'm coding my game using a client-server model. When playing on singleplayer, the game starts a local server, and interacts with it just like a remote server (multiplayer). I have done this to avoid coding separate singleplayer and multiplayer code. I have just started coding and have encountered a major problem. Currently I'm developing the game in Eclipse, having all the game classes organized into packages. Then, in my server code, I just use all the classes in the client packages. The problem is, these client classes have variables that are specific to rendering, which obviously wouldn't be performed on a server. Should I create modified versions of the client classes to use in the server? Or should I just modify the client classes with a boolean, to indicate if its the client/server using it. Are there any other options I have? I just had a thought about maybe using the server class as the core class, then extending it with rendering stuff?

    Read the article

  • Should I amortize scripting cost via bytecode analysis or multithreading?

    - by user18983
    I'm working on a game sort of thing where users can write arbitrary code for individual agents, and I'm trying to decide the best way to divide up computation time. The simplest option would be to give each agent a set amount of time and skip their turn if it elapses without an action being decided upon, but I would like people to be able to write their agents decision functions without having to think too much about how long its taking unless they really want to. The two approaches I'm considering are giving each agent a set number of bytecode instructions (taking cost into account) each timestep, and making players deal with the consequences of the game state changing between blocks of computation (as with Battlecode) or giving each agent it's own thread and giving each thread equal time on the processor. I'm about equally knowledgeable on both concurrency and bytecode stuff, which is to say not very, so I'm wondering which approach would be best. I have a clearer idea of how I'd structure things if I used bytecode, but less certainty about how to actually implement the analysis. I'm pretty sure I can work up a concurrency based system without much trouble, but I worry it will be messier with more overhead and will add unnecessary complexity to the project.

    Read the article

  • JavaScript Metaprogramming: Reduce boilerplate of adding functions to a function queue

    - by thurn
    I'm working with animation in JavaScript, and I have a bunch of functions you can call to add things to the animation queue. Basically, all of these functions look like this: function foo(arg1, arg2) { _eventQueue.push(function() { // actual logic } } I'm wondering now if it would be possible to cut down on this boilerplate a little bit, though, so I don't need that extra "_eventQueue" line in the function body dozens of times. Would it be possible, for example, to make a helper function which takes an arbitrary function as an argument and returns a new function which is augmented to be automatically added to the event queue? The only problem is that I need to find a way to maintain access to the function's original arguments in this process, which is... complicated.

    Read the article

  • Metaprogramming on web server

    - by bobobobo
    From time to time, I find myself writing server code that produces JavaScript code as the output result. I can point out why it is really bad: Inextricable tie between server code and client code. Can render client code un-reusable. But sometimes, it just seems to make sense. And isn't it kinda sorta interesting? I guess the question is, is writing server code that produces JavaScript code a really bad practice, or "does everyone do it"?

    Read the article

  • Template metaprogram converting type to unique number

    - by daramarak
    I just started playing with metaprogramming and I am working on different tasks just to explore the domain. One of these was to generate a unique integer and map it to type, like below: int myInt = TypeInt<AClass>::value; I want to know if this is at all possible, and in that case how. Because although I have learned much about exploring this subject I still have failed to come up with an answer. (P.S. A yes/no answer is much more gratifying than a c++ solution that doesn't use metaprogramming, as this is the domain that I am exploring)

    Read the article

  • C++ MPL or_, and_ implementations

    - by KRao
    Hi, I am trying to read the boost headers to figure out how they managed to implement the or_<...> and and_<...> metafunctions so that: 1) They can have an arbitrary number of arguments (ok, say up to 5 arguments) 2) They have short circuit behavior, for example: or_<false_,true_,...> does not instantiate whatever is after true_ (so it can also be declared but not defined) Unfortunately the pre-processor metaprogramming is making my task impossible for me :P Thank you in advance for any help/suggestion.

    Read the article

  • Reordering Variadic Parameters

    - by void-pointer
    I have come across the need to reorder a variadic list of parameters that is supplied to the constructor of a struct. After being reordered based on their types, the parameters will be stored as a tuple. My question is how this can be done so that a modern C++ compiler (e.g. g++-4.7) will not generate unnecessary load or store instructions. That is, when the constructor is invoked with a list of parameters of variable size, it efficiently pushes each parameter into place based on an ordering over the parameters' types. Here is a concrete example. Assume that the base type of every parameter (without references, rvalue references, pointers, or qualifiers) is either char, int, or float. How can I make it so that all the parameters of base type char appear first, followed by all of those of base type int (which leaves the parameters of base type float last). The relative order in which the parameters were given should not be violated within sublists of homogeneous base type. Example: foo::foo() is called with arguments float a, char&& b, const float& c, int&& d, char e. The tuple tupe is std::tuple<char, char, int, float, float>, and it is constructed like so: tuple_type{std::move(b), e, std::move(d), a, c}. Consider the struct defined below, and assume that the metafunction deduce_reordered_tuple_type is already implemented. How would you write the constructor so that it works as intended? If you think that the code for deduce_reodered_tuple_type, would be useful to you, I can provide it; it's a little long. template <class... Args> struct foo { // Assume that the metafunction deduce_reordered_tuple_type is defined. typedef typename deduce_reordered_tuple_type<Args...>::type tuple_type; tuple_type t_; foo(Args&&... args) : t_{reorder_and_forward_parameters<Args>(args)...} {} }; Edit 1 The technique I describe above does have applications in mathematical frameworks that make heavy use of expression templates, variadic templates, and metaprogramming in order to perform aggressive inlining. Suppose that you wish to define an operator that takes the product of several expressions, each of which may be passed by reference, reference to const, or rvalue reference. (In my case, the expressions are conditional probability tables and the operation is the factor product, but something like matrix multiplication works suitably as well.) You need access to the data provided by each expression in order to evaluate the product. Consequently, you must move the expressions passed as rvalue references, copy the expressions passed by reference to const, and take the addresses of expressions passed by reference. Using the technique I describe above now poses several benefits. Other expressions can use uniform syntax to access data elements from this expression, since all of the heavy-lifting metaprogramming work is done beforehand, within the class. We can save stack space by grouping the pointers together and storing the larger expressions towards the end of the tuple. Implementing certain types of queries becomes much easier (e.g. check whether any of the pointers stored in the tuple aliases a given pointer). Thank you very much for your help!

    Read the article

  • Metaprograming - self explanatory code - tutorials, articles, books

    - by elena
    Hello everybody, I am looking into improving my programming skils (actually I try to do my best to suck less each year, as our Jeff Atwood put it), so I was thinking into reading stuff about metaprogramming and self explanatory code. I am looking for something like an idiot's guide to this (free books for download, online resources). Also I want more than your average wiki page and also something language agnostic or preferably with Java examples. Do you know of such resources that will allow to efficiently put all of it into prectice (I know experience has a lot to say in all of this but i kind of want to build experience avoiding the flow bad decitions - experience - good decitions)? Thank you!

    Read the article

  • How do you pass variables to class_eval in ruby?

    - by klochner
    I'm working on a metaprogramming task, where I'm trying to use a single method to define a polymorphic association in the calling class, while also defining the association in the target class. I need to pass in the name of the calling class to get the association right. Here's a snippet that should get the idea across: class SomeClass < ActiveRecord::Base has_many :join_models, :dependent=:destroy end class JoinModel < ActiveRecord::Base belongs_to :some_class belongs_to :entity, :polymorphic=true end module Foo module ClassMethods def acts_as_entity has_many :join_models, :as=:entity, :dependent=:destroy has_many :some_classes, :through=:join_models klass = self.name.tableize SomeClass.class_eval "has_many :#{klass}, :through=:join_models" end end end I'd like to eliminate the klass= line, but don't know how else to pass a reference to self from the calling class into class_eval. any suggestions?

    Read the article

  • Programmatically create static arrays at compile time in C++

    - by Hippicoder
    One can define a static array at compile time as follows: const std::size_t size = 5; unsigned int list[size] = { 1, 2, 3, 4, 5 }; Question 1 - Is it possible by using various kinds of metaprogramming techniques to assign these values "programmatically" at compile time? Question 2 - Assuming all the values in the array are to be the same barr a few, is it possible to selectively assign values at compile time in a programmatic manner? eg: const std::size_t size = 7; unsigned int list[size] = { 0, 0, 2, 3, 0, 0, 0 }; Solutions using C++0x are welcome The array may be quite large, few hundred elements long The array for now will only consist of POD types It can also be assumed the size of the array will be known beforehand, in a static compile-time compliant manner. Solutions must be in C++ (no script or codegen based solutions)

    Read the article

  • How do you pass self to class_eval in ruby?

    - by klochner
    I'm working on a metaprogramming task, where I'm trying to use a single method to define a polymorphic association in the calling class, while also defining the association in the target class. I need to pass in the name of the calling class to get the association right. Here's a snippet that should get the idea across: class SomeClass < ActiveRecord::Base has_many :join_models, :dependent=:destroy end class JoinModel < ActiveRecord::Base belongs_to :some_class belongs_to :entity, :polymorphic=true end module Foo module ClassMethods def acts_as_entity has_many :join_models, :as=:entity, :dependent=:destroy has_many :some_classes, :through=:join_models klass = self.name.tableize SomeClass.class_eval "has_many :#{klass}, :through=:join_models" end end end I'd like to eliminate the klass= line, but don't know how else to pass a reference to self from the calling class into class_eval. any suggestions?

    Read the article

  • Why can't I pass self as a named argument to an instance method in Python?

    - by Joseph Garvin
    This works: >>> def bar(x, y): ... print x, y ... >>> bar(y=3, x=1) 1 3 And this works: >>> class foo(object): ... def bar(self, x, y): ... print x, y ... >>> z = foo() >>> z.bar(y=3, x=1) 1 3 And even this works: >>> foo.bar(z, y=3, x=1) 1 3 But why doesn't this work? >>> foo.bar(self=z, y=3, x=1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method bar() must be called with foo instance as first argument (got nothing instead) This makes metaprogramming more difficult, because it requires special case handling. I'm curious if it's somehow necessary by Python's semantics or just an artifact of implementation.

    Read the article

  • SFINAE + sizeof = detect if expression compiles

    - by FredOverflow
    I just found out how to check if operator<< is provided for a type. template<class T> T& lvalue_of_type(); template<class T> T rvalue_of_type(); template<class T> struct is_printable { template<class U> static char test(char(*)[sizeof( lvalue_of_type<std::ostream>() << rvalue_of_type<U>() )]); template<class U> static long test(...); enum { value = 1 == sizeof test<T>(0) }; typedef boost::integral_constant<bool, value> type; }; Is this trick well-known, or have I just won the metaprogramming Nobel prize? ;) EDIT: I made the code simpler to understand and easier to adapt with two global function template declarations lvalue_of_type and rvalue_of_type.

    Read the article

  • In Ruby or Python can the very idea of Class be rewritten?

    - by John Berryman
    Howdy All... first time at stack overflow. I'm looking into using some of the metaprogramming features provided by Ruby or Python, but first I need to know the extent to which they will allow me to extend the language. The main thing I need to be able to do is to rewrite the concept of Class. This doesn't mean that I want to rewrite a specific class during run time, but rather I want to make my own conceptualization of what a Class is. To be a smidge more specific here, I want to make something that is like what people normally call a Class, but I want to follow an "open world" assumption. In the "closed world" of normal Classes, if I declare Poodle to be a subclass of Dog to be a subclass of Animal, then I know that Poodle is not going to also be a type of FurCoat. However, in an open world Class, then the Poodle object I've defined may or may not be and object of type FurCoat and we won't know for sure until I explain that I can wear the poodle. (Poor poodle.) This all has to do with a study I'm doing concerning OWL ontologies. Just so you know, I've tried to find information online, but due to the overloading of terms here I haven't found anything helpful. Super thanks, John

    Read the article

  • Understanding the singleton class when aliasing a instance method

    - by Backo
    I am using Ruby 1.9.2 and the Ruby on Rails v3.2.2 gem. I am trying to learn Metaprogramming "the right way" and at this time I am aliasing an instance method in the included do ... end block provided by the RoR ActiveSupport::Concern module: module MyModule extend ActiveSupport::Concern included do # Builds the instance method name. my_method_name = build_method_name.to_sym # => :my_method # Defines the :my_method instance method in the including class of MyModule. define_singleton_method(my_method_name) do |*args| # ... end # Aliases the :my_method instance method in the including class of MyModule. singleton_class = class << self; self end singleton_class.send(:alias_method, :my_new_method, my_method_name) end end "Newbiely" speaking, with a search on the Web I came up with the singleton_class = class << self; self end statement and I used that (instead of the class << self ... end block) in order to scope the my_method_name variable, making the aliasing generated dynamically. I would like to understand exactly why and how the singleton_class works in the above code and if there is a better way (maybe, a more maintainable and performant one) to implement the same (aliasing, defining the singleton method and so on), but "the right way" since I think it isn't so.

    Read the article

  • C# - Recursive / Reflection Property Values

    - by tyndall
    What is the best way to go about this in C#? string propPath = "ShippingInfo.Address.Street"; I'll have a property path like the one above read from a mapping file. I need to be able to ask the Order object what the value of the code below will be. this.ShippingInfo.Address.Street Balancing performance with elegance. All object graph relationships should be one-to-one. Part 2: how hard would it be to add in the capability for it to grab the first one if its a List< or something like it.

    Read the article

  • java annotations: library to override annotations with xml files

    - by flybywire
    Java has annotations and that is good. However, some developers feel that it is best to annotate code with metadata using xml files - others prefer annotations but would use metadata to override annotations in source code. I am writing a Java framework that uses annotations. The question is: is there a standard way to define and parse metadata from xml files. I think this is something every framework that uses annotations could benefit from but I can seem to find something like this on the Internet. Must I roll my own xml parsing/validation or has someone already done something like this?

    Read the article

  • List stored functions using a table in PostgreSQL

    - by Paolo B.
    Just a quick and simple question: in PostgreSQL, how do you list the names of all stored functions/stored procedures using a table using just a SELECT statement, if possible? If a simple SELECT is insufficient, I can make do with a stored function. My question, I think, is somewhat similar to this other question, but this other question is for SQL Server 2005: http://stackoverflow.com/questions/119679/list-of-stored-procedure-from-table (optional) For that matter, how do you also list the triggers and constraints that use the same table in the same manner?

    Read the article

< Previous Page | 1 2 3 4 5 6 7  | Next Page >