3-15 《元编程》第6章 3-16 hook method

Code That Writes Code 

6.1 Coding your way to the weekend

 

6.2 Kernel#eval, Binding#eval 

Binding:

Objects of class Binding(类Binding的对象) encapsulate (密封)the execution context at some particular place in the code and retain this context for future use.

 

如果你想要一段已经执行的代码在今后反复使用,可以用Binding对象封装它。

The variables, methods, value of self, and possibly an iterator block(迭代块) that can be accessed in this context are all retained. 

变量,方法,自身的value,甚至迭代块都可以用Binding对象封装储存。

Binding objects can be created using Kernel#binding

 

eval(string [, filename [,lineno]]) → obj

Evaluates the Ruby expression(s) in string, in the binding's context.

Binding对象的eval方法,可以评估字符串内的Ruby表达式,并返回表达式的值。

If the optional filename and lineno parameters are present, they will be used when reporting syntax errors.

 

class Myclass
  def my_method
    @x = 1
  binding
  end
end
p b = Myclass.new.my_method
p b.eval("@x")
p eval("@x", b)

#结果一样 1

 

class Anotherclass
  def my_method
    # eval "self", TOPLEVEL_BINDING   #=> main
    eval("xx + yy", TOPLEVEL_BINDING)
  end
end
xx = 123
yy = 321
obj = Anotherclass.new
p obj.my_method #=> 444

TOPLEVEL_BINDING: 是预定义常量,表示顶层作用域的Binding对象。

 

6.24 Strings of Code Vs Blocks 

 eval只能执行代码字符串,instance_eval和class_eval可以执行代码字符串和block

array = [1,2,3]
x = 'd'
array.instance_eval("self[1] = x")
p array #=> [1, "d", 3]
尽量用block,代码字符串安全性低容易被攻击。同时也难以阅读和修改。

 

流行的做法是禁止使用eval方法,同时用Dynamic methods和Dynamic Dispatch替代

 

污染对象 

Ruby把外部传入的对象标记为污染对象。Object#taint -> obj.

判断: #tainted? ->true/false

去掉污染 #untaint 

 

谨慎使用安全级别p148页

可以使用proc {}.call 作为洁净室

 


 

6.3Hook Method: 

Class#inherited是一个实例方法,当一个类被继承时,Ruby会调用这个方法,Class#inherited方法什么也不做,但程序员可以覆写它的行为,像这样的方法称为钩子方法。

inherited(subclass):Callback invoked whenever a subclass of the current class is created.

更多的钩子方法:

Module#included,#prepended,#method_added, #method_removed, #method_undefined (只对实例方法有用),#singleton_method_added...

 

这种钩子方法写在模块里,用类方法的方式定义:

module M1
  def self.included(othermod)
    puts "m1 was included into #{othermod}"
  end
end
class C
  include M1
end
#=>m1 was included into C

另外一种方式钩住同一个事件,:#include方法可以覆写 ,但注意写在类C中。

我的理解类C.调用include方法,就是self.include。先是在自身调用覆写的include方法,然后用super关键字调用原始方法。

⚠️ 类方法是不能被继承的只能自己用。

⚠️ 类包含模块后默认是获得实例方法。除非用#extend

module M
  def hello
    puts "world"
  end
end
class C
  def self.include(mod)
    puts "Called: C.include(#{mod})"
    super  #因为覆写了include,所以需要用super调用原始的include功能,否则M不会被C包含
  end 
  include(M)
end
C.new.hello✅

 类方法和钩子方法结合的技巧:P160页。 

转载于:https://www.cnblogs.com/chentianwei/p/8574545.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/250793.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

7 useLayoutEffect、useDebugValue

useEffect:dom完成渲染后执行 不传参数,每次都会执行 传空的依赖[],只会执行一次 有依赖,依赖项变化会执行 useEffect实现动画效果 import { useEffect, useRef, useState } from "react"const App () > {const [,…

【Linux】用户与权限

追加用户组 groupadd 用户组名 追加新用户 useradd -d 指定用户目录 -s 指定用户使用shell -g 指定用户组 -p 指定用户密码 用户名 更改用户 添加用户到其他组 usermod -G 用户组 用户名 修改用户密码 passwd 用户名 删除用户 userdel [参数] 用户名参数:-f&#x…

es6 --- map的使用

思路: 1.使用一个map数组来保存nums1中出现的元素及其次数. 2.遍历nums2.使用map的has方法来检测nums2中的元素是否出现在map中,若出现则加入返回数组(retArr),且map数组中的次数减1 /*** param {number[]} nums1* param {number[]} nums2* return {number[]}*/ var intersect…

NOIP2005普及组第3题 采药 (背包问题)

NOIP2005普及组第3题 采药    时间限制: 1 Sec 内存限制: 128 MB提交: 50 解决: 23[提交][状态][讨论版][命题人:外部导入]题目描述 辰辰是个天资聪颖的孩子,他的梦想是成为世界上最伟大的医师。为此,他想拜附近最有威望的医师为师。医师为了判断他…

前端面试之Vue相关总结

Vue2中检测数组变化的限制和解决方法 vue2用下标设置数组没效果 arr [1,2] arr[0] 0,页面上显示的arr并没有修改(如果对应下标是原始值;若是引用值)解决1:Vue.Set解决2:arr.splice (Vue会劫持splice方法) Vue2对对象是循环defineProperty…

JS和安卓 IOS的交互 例子式记录

(function () { var u navigator.userAgent; var isAndroid u.indexOf(Android) > -1 || u.indexOf(Adr) > -1; //android终端 var isiOS !!u.match(/\(i[^;];( U;)? CPU.Mac OS X/); if(isAndroid){ (function(){ function android_i…

vue --- ref属性获取dom元素和子组件的方法

说明: // 假设login的组件定义如下: Vue.component(login, {template:<h1>登录</h1>,data(){return {msg:son msg,}},methods(){show(){console.log(调用子组件的方法);}} }) // 在父元素中使用 <div id"app"><login ref"myLogin"&g…

【工程师综合项目二】React + Koa2打造『JS++官网管理后台』

Redis认知、安装与操作 MongoDB&#xff1a;动态数据库&#xff0c;如游戏中需要频繁地保存人物的坐标 Oracle&#xff1a;收费&#xff0c;企业级 mac要安装homebrew&#xff08;包管理工具&#xff09; window安装Redis程序运行教程 命令行Redis操作 启动&#xff1a; redis-…

webpack --- html-webpack-plugin

安装 cnpm i html-webpack-plugin -D配置 (webpack.config.js) // webpack 是基于node构建的,webpack的配置文件中,任何合法的Node代码都是支持的 var path require(path)// 在内存中生成src下的index.html,同时自动将打包好的bundle.js 导入到页面中 var htmlWebpackPlugin…

nyoj164——卡特兰数(待填坑)

题意&#xff1a;将1~2n个数按照顺时针排列好&#xff0c;用一条线将两个数字连接起来要求&#xff1a;线之间不能有交点&#xff0c;同一个点只允许被连一次。 最后问给出一个n&#xff0c;有多少种方式满足条件。 卡特兰数&#xff08;列&#xff09;&#xff1a; 令h(0)1,h(…

git 使用

1. 先进入项目文件夹&#xff0c;通过命令 git init 把这个目录变成git可以管理的仓库 git init 2. 把文件添加到版本库中&#xff0c;使用命令 git add .添加到暂存区里面去&#xff0c;不要忘记后面的小数点“.”&#xff0c;意为添加文件夹下的所有文件 git add . 3. 用命令…

webpack --- 使用vue

// webpack中如何使用 vue: // 1. 安装vue 的包: cnpm i vue -S // 2. 由于在 webpack 中,推荐使用 . vue 这个组件模板文件定义组件, 所以需要安装能解析这种文件的loader cnpm i vue-loader vue-template-compiler -D // 3. 在main.js 中导入 vue的包, import Vue from vue…

ES6杂碎

1、let声明的变量没有变量提升&#xff1b; 2、const声明的变量&#xff1a;块级作用域内有效&#xff0c;存在暂时性死区&#xff0c;变量指向的那个内存地址不得改动&#xff1b; 3、...tail解构出来的是数组或空数组 let [head, ...tail] [1, 2, 3, 4]; head //1 tail //[2…

koa --- 自制简易的koa-router

打算自己写一个简单的Router类,来实现koa-router这个中间件的(部分)神奇功能 确定需求 1.首先导入需要在app.js里面导入自己写的Router类 2.然后是使用的方式和挂载router的方式 // 导入Router类 const Router require(./components/router.js);// 使用方式,(暂时只对get请…

MariaDB 脚本

研究MariaDB&#xff0c; 需要mock up一些假数据&#xff1a; 生成n个长度整型数的函数rand_num&#xff1a; CREATE DEFINERrootlocalhost FUNCTION rand_num(n INT) RETURNS int(5) begin DECLARE i INT DEFAULT 0; DECLARE result INT DEFAULT 0; WHILE i < n DOSET re…

Promise的基本使用

利用Promise是解决JS异步执行时候回调函数嵌套回调函数的问题&#xff0c; 更简洁地控制函数执行流程&#xff1b; 通过new实例化Promise&#xff0c; 构造函数需要两个参数&#xff0c; 第一个参数为函数执行成功以后执行的函数resolve&#xff0c; 第二个函数为函数执行失败…

软工作业PSP与单元测试训练

一、实现模块判断传入的身份证号码的正确性&#xff1b; 二、针对所实现的模块编写对应的单元测试代码&#xff1b; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; import java.u…

koa --- nunjucks

安装: npm install koa-nunjucks-2 --save目录结构 |--- controller/ | |--- home.js |--- service/ | |--- home.js |--- views/ |--- app.js |--- router.jsapp.js // (部分) const nunjucks require(koa-nunjucks-2); app.use(nunjucks({ext: html,path: path.joi…

DNN模型训练词向量原理

转自&#xff1a;https://blog.csdn.net/fendouaini/article/details/79821852 1 词向量 在NLP里&#xff0c;最细的粒度是词语&#xff0c;由词语再组成句子&#xff0c;段落&#xff0c;文章。所以处理NLP问题时&#xff0c;怎么合理的表示词语就成了NLP领域中最先需要解决的…

天平称重【递归解法】

用天平称重时&#xff0c;我们希望用尽可能少的砝码组合称出尽可能多的重量。如果只有5个砝码&#xff0c;重量分别是1&#xff0c;3&#xff0c;9&#xff0c;27&#xff0c;81则它们可以组合称出1到121之间任意整数重量&#xff08;砝码允许放在左右两个盘中&#xff09;。 本…