template auto func(Args... args) { return (args || ... );
std::cout << func("str");
Does it compile? What will be the output?
Answers in the article :)
Fold expressions exist in C++ since C++17 and significantly affect how we treat variadic templates. Back in the day, I wrote about fold-expressions as part of the metaprogramming series, but today we will explore the extreme cases of fold-expression usages.
An important disclaimer before we start: In this article, code examples show variadic template usages with arguments passed by value,âŠ
Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
â Live Streamingâ Interactive Chatâ Private Showsâ HD Quality
Anya is LIVE right now
FREE
Free to watch âą No registration required âą HD streaming
W3D5: Cogitating Upon My Corpus Callosum Alone I Record a Record of Meta-Programming Solo to Encode My Own ActiveRecord
Friday we had our first day coding solo, as opposed to the paired programming exercises in which we usually engage. Â Our lecture covered meta-programming (writing code which, when executed, writes new methods, essentially code encoding code). Â We then used meta-programming to encode our own version of the gem weâve been using to call SQL commands in rails this week, ActiveRecord. Â The purpose of this would seem to be twofold: we have the opportunity to practice meta-programming, and we gain a much deeper understanding of the functionality of ActiveRecord by having to write the thing ourselves. Â While at first I was thrilled to plug one of the school monitors into my laptop, put my headphones in, and go at my own pace, it wasnât long before I began to miss the benefit of a second pair of eyes and cerebral hemispheres to spot mistakes and find new approaches to problems. Â Having practiced so much, and overcome so many challenges, as a member of a pair, coding alone again was mildly like a lobotomy. Â Cut off from my other hemisphere, I approached problems in a more brute-force manner, and started to get a little frustrated with the fact that the TAâs had to field (at least) twice as many questions as usual and were therefore (at most) half as available, until it occurred to me to swallow my pride and just ask those working solo around me for guidance to get over a few humps. Â
I imagine this is good practice for the professional world, as I will often have to code alone, and I need not hesitate to ask others to give my work a fresh set of eyes or help me get unstuck (and indeed to foster relationships in which such interactions are reciprocal)... but Iâm looking forward to having a partner again tomorrow.
Rendons le paramĂštre context de TinyTemplate() optionnel. Dans le cas oĂč il est omis, nous retrouvons le contexte de lâappelant Ă l'aide de RubyVM::DebugInspector.
Aurions-nous le moyen de raccourcir davantage cette syntaxe ? Oui, en utilisant un objet existant, qui nâest autre que la chaine de caractĂšre du template Ă parser !
> irb
>>Â $:
>>Â require 'secure_shell'
>>Â require 'securerandom'
>>Â begin
>>Â Â Â using SecureShell
>>
>>Â Â Â backstick('git init '.shell_safe! + SecureRandom.hex(20).shellescape)
>>Â end
NoMethodError: undefined method `shell_safe?' for "git init ":String
  from /Users/Ihcene/aritylabs/secure_shell/secure_shell.rb:48:in `+'
It's official: C++11 has two meta-programming languages embedded in it! One is based on templates and other one using constexpr. Templates have been extensively used for meta-programming in C++03. C++11 now gives you one more option of writing compile-time meta-programs using constexpr. The capabilities differ, however.
Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
â Live Streamingâ Interactive Chatâ Private Showsâ HD Quality
Anya is LIVE right now
FREE
Free to watch âą No registration required âą HD streaming
Recently I had a requirement in an application I was working on to add an internal Settings model. By my own standards, I wanted it to be very lightweight and flexible. There are several gems that provide such drop-in functionality, such as https://github.com/Squeegy/rails-settings or https://github.com/railsjedi/rails_config. However, I felt this added an unnecessary dependency to our project for a seemingly simple feature.
Instead, I ventured to create our own ActiveRecord Based Settings Model. I went in knowing that it needed to be lightweight and flexible. The following is a brief walkthrough of how I went about implementing a Settings model that ultimately has one record in the Settings table and leverages Ruby's dynamic programming to create attributes when required.
The Migration
class CreateSettings < ActiveRecord::Migration def change create_table :settings do |t| t.text :preferences t.timestamps end end end
Pretty straightforward here. Only one column in addition to the timestamps, :preferences. This will be a serialized field allowing me to enter in key value pairs in a hash.
The Pseudo-Singleton
I wanted to ensure that there would never be more than one record in the Settings table, but didn't feel the single Settings object would be accessed often enough to warrant a proper Singleton instantiation. Instead, I added the following to the Settings Model:
class Settings < ActiveRecord::Base ... before_create :confirm_singularity ... def confirm_singularity raise Exception.new("A Setting record already exists") if Settings.count > 0 end end
This simple bit of code ensures that an exception will be raised if an attempt to create a Settings beyond the first is made.
Leveraging Method Missing
I wanted to allow that single Settings preferences Hash to not rely on predefined keys. Rather, it would be far more flexible for any key to be set throughout the lifetime of the application. To achieve this I relied upon method_missing:
def self.method_missing(method, *args) method_name = method.to_s super(method, *args) rescue NoMethodError settings = self.first_or_create if method_name =~ /=$/ name = method_name.gsub('=', '') value = args.first settings.preferences[name.to_sym] = value settings.save else settings.preferences[method_name.to_sym] end end
In this method, when a method that is not found is caught by the 'NoMethodError'. Once caught, I first retrieve or create the settings record. This allows for anyone to assign settings without needing to worry about whether a Setting record has been created or not.
From there I employ a regex to determine whether the method sent to Settings is a setter and thus contains a '='. If it is then I parse the name of the method from the method, and assign the value of the key as the first of args. Then I access the settings.preferences Hash and add the key value pair and subsequently save the settings record.
In the case that the method sent to Settings is a getter, then the else statement simple retrieves and returns the value of the key from settings.preferences.
Conclusion
After completing this task of implementing a flexible Settings model. I felt far more comfortable with Ruby's dynamic/meta programming. Of course there is an overhead cost to dynamic programming, but I feel that for something as innocuous as application settings it was worth it.
I encourage anyone reading this to offer comments and criticisms or other examples of where you've done something similar.
3rd straight day of solo work. This whole week has been building variations of Rails projects, so today was a nice change, as we did something a bit more technical. Our old friend meta-programming returned for the day, and it was a welcome sight. The task was to build an itty-bitty ActiveRecord. Exactly two weeks ago, as we were getting up to speed on SQL, we had built a our own ORM, but it was domain-specific and not reusable. Today, we were challenged to build a small framework that could be used to map data of any type from the database into Rails.
250,000. That's how many lines of code ActiveRecord encompasses. Far be it for us to judge, but after completing today's project, that does seem a bit excessive. In 250 lines, I was able to implement the following features:
attribute_setters
belongs_to association
has_many association
has_one_through association
find record
all records
where (search records by single or multiple criteria)
save (with update & create, as appropriate)
This was a more advanced form of meta-programming than I had attempted before, having had my dalliances with it all throughout the week as I tried to spruce up my individual projects. When we reached the has_one_through feature, I really appreciated the step-by-step curation of the materials. Up to that point I had ironed out the framework, more or less, on my own.
What we did today gave us a valuable view into how ActiveRecord does its magic. You could say it tore back the veil on Oz. Word on the street is that next week we may do the same thing to Rails routing: uncover Rails piece by piece until it's no longer magical. With great power comes great responsibility, and once we uncloak the wizard we very well may don his robes. I, for one, would not mind some wizarding in my career.
Week 5, Day 5-7: Ending Rails with a Bang and Embarking on JS
Exercise:Â ActiveRecord (meta-programming)
Building Active Record Lite
Today's project was the probably the hardest one we've had so far: We built our own lightweight ActiveRecord class. Â The three main things I got out of this project were:
1) Demystifying Rails associations and truly understand what's happening at the Ruby level.
2) Practice at meta-programming in Ruby; knowing how to use send, define_method, and constantize.
3) Practice with using class inheritance and modules to organize code in a large-scale project. Â I gained more program architecture intuition as I Â learned how to use nested classes and module mix-ins to DRY things up.
Enter the Javascript
Next week we start on Javascript, which I'm looking forward to just for the change.  This weekend I went through Code Academy's Javascript lessons.  It's fun to learn another language after gaining fluency in Ruby.  So far, the biggest difference I notice is that Javascript has objects, but no classes.  In some ways, Javascript reminds me of my first programming language, which was MATLAB (a very high level language).  They both seem to be pass-by-value languages and they both use "function" to define methods.  They both are languages in a confined environment (browser and workspace, respectively).  These similarities may be very superficial so we'll see in the coming week.